var VECleaner;
(function (VECleaner) {
    var Translator = (function () {
        function Translator() {
            this.mData = null;
        }
        Translator.prototype.loadData = function (data) {
            this.mData = JSON.parse(data);
        };
        Translator.prototype.format = function (str) {
            var restOfname = [];
            for (var _i = 1; _i < arguments.length; _i++) {
                restOfname[_i - 1] = arguments[_i];
            }
            if (restOfname.length > 0) {
                var index = 1;
                var localizedStr = str;
                while (localizedStr.indexOf("$" + index) !== -1) {
                    localizedStr = localizedStr.replace("$" + index, restOfname[index - 1]);
                    index++;
                }
                return localizedStr;
            }
            else {
                return str;
            }
        };
        return Translator;
    }());
    VECleaner.kTranslator = new Translator();
    var ArrayUtils = (function () {
        function ArrayUtils() {
        }
        ArrayUtils.DoesArrayContain = function (arr, element, compare) {
            if (compare === void 0) { compare = null; }
            if (compare != null) {
                for (var i = 0; i < arr.length; i++) {
                    if (compare(arr[i], element)) {
                        return true;
                    }
                }
            }
            else {
                for (var i = 0; i < arr.length; i++) {
                    if (arr[i] == element) {
                        return true;
                    }
                }
            }
            return false;
        };
        ArrayUtils.RemoveArrayElement = function (arr, element, compare) {
            if (compare === void 0) { compare = null; }
            if (compare != null) {
                for (var i = 0; i < arr.length; i++) {
                    if (compare(arr[i], element)) {
                        arr.splice(i, 1);
                    }
                }
            }
            else {
                for (var i = 0; i < arr.length; i++) {
                    if (arr[i] == element) {
                        arr.splice(i, 1);
                    }
                }
            }
        };
        return ArrayUtils;
    }());
    var JsonWriter = (function () {
        function JsonWriter() {
            this.mContent = "";
        }
        JsonWriter.prototype.removeLastComma = function () {
            var last = this.mContent.charAt(this.mContent.length - 1);
            if (last == ",") {
                this.mContent = this.mContent.substr(0, this.mContent.length - 1);
            }
        };
        JsonWriter.prototype.putKey = function (key) {
            this.mContent += "\"" + key + "\":";
        };
        JsonWriter.prototype.putNumber = function (num) {
            this.mContent += num.toString() + "";
            this.mContent += ",";
        };
        JsonWriter.prototype.putString = function (str) {
            this.mContent += JSON.stringify(str);
            this.mContent += ",";
        };
        JsonWriter.prototype.putPureString = function (str) {
            this.mContent += "\"" + str + "\"";
            this.mContent += ",";
        };
        JsonWriter.prototype.putBoolean = function (bool) {
            this.mContent += bool.toString();
            this.mContent += ",";
        };
        JsonWriter.prototype.startArray = function () {
            this.mContent += "[";
        };
        JsonWriter.prototype.endArray = function () {
            this.removeLastComma();
            this.mContent += "],";
        };
        JsonWriter.prototype.startObject = function () {
            this.mContent += "{";
        };
        JsonWriter.prototype.endObject = function () {
            this.removeLastComma();
            this.mContent += "},";
        };
        JsonWriter.prototype.getContent = function () {
            var last = this.mContent.charAt(this.mContent.length - 1);
            if (last == ",") {
                return this.mContent.substr(0, this.mContent.length - 1);
            }
            else {
                return this.mContent;
            }
        };
        JsonWriter.prototype.writeToFile = function (path) {
            var file = new File(path);
            file.open("w");
            file.encoding = "utf-8";
            file.write(this.mContent);
            file.close();
        };
        return JsonWriter;
    }());
    var DomUtils = (function () {
        function DomUtils() {
        }
        DomUtils.GetCurrentItem = function () {
            var proj = app.project;
            if (proj != null) {
                var comp = proj.activeItem;
                return comp;
            }
            return null;
        };
        DomUtils.GetCurrentComp = function () {
            var item = this.GetCurrentItem();
            if (item && item instanceof CompItem) {
                return item;
            }
            return null;
        };
        DomUtils.GetSelectedLayers = function () {
            var comp = this.GetCurrentComp();
            if (comp) {
                return comp.selectedLayers;
            }
            return null;
        };
        DomUtils.GetFirstSelectedLayer = function () {
            var layers = this.GetSelectedLayers();
            if (layers && layers.length > 0) {
                return layers[0];
            }
            return null;
        };
        DomUtils.GetLayersInComp = function (comp) {
            var layers = [];
            for (var i = 1; i <= comp.numLayers; i++) {
                layers.push(comp.layer(i));
            }
            return layers;
        };
        DomUtils.FindCompByName = function (name) {
            var proj = app.project;
            if (proj != null) {
                for (var i = proj.numItems; i > 0; i--) {
                    var comp = proj.item(i);
                    if (comp instanceof CompItem && comp.name == name) {
                        return comp;
                    }
                }
            }
            return null;
        };
        DomUtils.GetItemName = function (index) {
            var proj = app.project;
            if (proj != null) {
                if (index >= 1 && index <= proj.numItems) {
                    return proj.item(index).name;
                }
            }
            return null;
        };
        DomUtils.GetItemById = function (id) {
            var proj = app.project;
            if (proj != null) {
                for (var i = proj.numItems; i > 0; i--) {
                    if (proj.item(i).id == id) {
                        return proj.item(i);
                    }
                }
            }
            return null;
        };
        DomUtils.GetItemByFile = function (file) {
            var proj = app.project;
            if (proj != null) {
                for (var i = proj.numItems; i > 0; i--) {
                    var item = proj.item(i);
                    if (item && item instanceof FootageItem && item.file && item.file.absoluteURI == file.absoluteURI) {
                        return item;
                    }
                }
            }
            return null;
        };
        DomUtils.GetCompByIndex = function (index) {
            var proj = app.project;
            if (proj != null) {
                if (index >= 1 && index <= proj.numItems) {
                    var comp = proj.item(index);
                    if (comp instanceof CompItem) {
                        return comp;
                    }
                }
            }
            return null;
        };
        DomUtils.GetCompIndexById = function (id) {
            var proj = app.project;
            if (proj != null) {
                for (var i = proj.numItems; i > 0; i--) {
                    var comp = proj.item(i);
                    if (comp instanceof CompItem && comp.id == id) {
                        return i;
                    }
                }
            }
            return null;
        };
        DomUtils.GetCompLayerName = function (compIndex, layer) {
            var proj = app.project;
            if (proj != null) {
                if (compIndex >= 1 && compIndex <= proj.numItems) {
                    var comp = proj.item(compIndex);
                    if (comp instanceof CompItem && layer >= 1 && layer <= comp.numLayers) {
                        return comp.layer(layer).name;
                    }
                }
            }
            return null;
        };
        DomUtils.RemoveLayerDisabledEffects = function (layer) {
            var count = 0;
            var e = layer.effect;
            for (var i = e.numProperties; i > 0; i--) {
                var f = e.property(i);
                if (!f.active) {
                    count++;
                    f.remove();
                    i--;
                }
            }
            return count;
        };
        DomUtils.RemoveLayerAllEffects = function (layer) {
            var e = layer.effect;
            while (e.numProperties > 0) {
                e.property(1).remove();
            }
        };
        DomUtils.IsLayerReallyHasEffects = function (layer) {
            if (layer.effect.numProperties > 0 && layer.effectsActive) {
                for (var ee = 1; ee <= layer.effect.numProperties; ee++) {
                    if (layer.effect.property(ee).enabled) {
                        return true;
                    }
                }
            }
            return false;
        };
        DomUtils.RemoveLayerAllStyles = function (layer) {
            var e = layer.layerStyle;
            for (var i = e.numProperties; i > 0; i--) {
                var f = e.property(i);
                if (f.enabled) {
                    f.enabled = false;
                }
            }
        };
        DomUtils.RemoveLayerAllMasks = function (layer) {
            var e = layer.mask;
            while (e.numProperties > 0) {
                e.property(1).remove();
            }
        };
        DomUtils.GetCamerasLayerInComp = function (comp) {
            var cameras = [];
            for (var i = 1, l = comp.numLayers; i <= l; i++) {
                var layer = comp.layer(i);
                if (layer instanceof CameraLayer && layer.enabled) {
                    cameras.push(layer);
                }
            }
            return cameras;
        };
        DomUtils.GetLightLayerInComp = function (comp) {
            var lights = [];
            for (var i = 1, l = comp.numLayers; i <= l; i++) {
                var layer = comp.layer(i);
                if (layer instanceof LightLayer) {
                    lights.push(layer);
                }
            }
            return lights;
        };
        DomUtils.AddDefaultCameraToComp = function (comp) {
            var layer = comp.layers.addCamera("Default Camera", [comp.width * 0.5, comp.height * 0.5]);
            var p = layer.position.value;
            layer.position.setValue([comp.width * 0.5, comp.height * 0.5, p[2]]);
            layer.pointOfInterest.setValue([comp.width * 0.5, comp.height * 0.5, 0]);
            layer.moveToEnd();
        };
        DomUtils.ReplacePrecompWithFile = function (oldItem, newFile) {
            var impOpt = new ImportOptions(newFile);
            var footageItem = app.project.importFile(impOpt);
            var comps = oldItem.usedIn;
            for (var c = 0; c < comps.length; c++) {
                var comp = comps[c];
                for (var l = 1; l <= comp.numLayers; l++) {
                    var layer = comp.layer(l);
                    if (layer instanceof AVLayer) {
                        if (layer.source.id == oldItem.id) {
                            layer.source.replaceSource(footageItem);
                        }
                    }
                }
            }
        };
        DomUtils.ReplaceFootageItem = function (oldFootage, newFile) {
            if (oldFootage) {
                oldFootage.replace(newFile);
            }
        };
        DomUtils.IsPrecompInsideMainComp = function (precomp, mainComp) {
            if (precomp.id == mainComp.id) {
                return true;
            }
            for (var i = 1; i <= mainComp.numLayers; i++) {
                var layer = mainComp.layer(i);
                if (layer instanceof AVLayer && layer.source instanceof CompItem) {
                    if (layer.source.id == precomp.id || DomUtils.IsPrecompInsideMainComp(precomp, layer.source)) {
                        return true;
                    }
                }
            }
            return false;
        };
        DomUtils.DisableCompAudio = function (comp) {
            var numLayers = comp.numLayers;
            for (var l = 1; l <= numLayers; l++) {
                var layer = comp.layer(l);
                if (layer instanceof AVLayer) {
                    layer.audioEnabled = false;
                }
            }
        };
        DomUtils.ShowItem = function (id) {
            var proj = app.project;
            if (proj != null) {
                for (var i = 1; i <= proj.numItems; i++) {
                    if (app.project.item(i).id == id) {
                        app.project.item(i).selected = true;
                    }
                    else {
                        app.project.item(i).selected = false;
                    }
                }
            }
        };
        return DomUtils;
    }());
    var LayerTypes;
    (function (LayerTypes) {
        LayerTypes[LayerTypes["kAVLayer"] = 1] = "kAVLayer";
        LayerTypes[LayerTypes["kCameraLayer"] = 2] = "kCameraLayer";
        LayerTypes[LayerTypes["kLightLayer"] = 4] = "kLightLayer";
        LayerTypes[LayerTypes["kShapeLayer"] = 8] = "kShapeLayer";
        LayerTypes[LayerTypes["kTextLayer"] = 16] = "kTextLayer";
        LayerTypes[LayerTypes["kPlaceholderStillLayer"] = 32] = "kPlaceholderStillLayer";
        LayerTypes[LayerTypes["kSolidLayer"] = 64] = "kSolidLayer";
        LayerTypes[LayerTypes["kStillLayer"] = 128] = "kStillLayer";
        LayerTypes[LayerTypes["kGuideLayer"] = 256] = "kGuideLayer";
        LayerTypes[LayerTypes["kAdjustmentLayer"] = 512] = "kAdjustmentLayer";
        LayerTypes[LayerTypes["kNullLayer"] = 1024] = "kNullLayer";
        LayerTypes[LayerTypes["kAudioLayer"] = 2048] = "kAudioLayer";
        LayerTypes[LayerTypes["kPreCompLayer"] = 4096] = "kPreCompLayer";
        LayerTypes[LayerTypes["kPlaceholderVideoLayer"] = 8192] = "kPlaceholderVideoLayer";
        LayerTypes[LayerTypes["kImageSequenceLayer"] = 16384] = "kImageSequenceLayer";
        LayerTypes[LayerTypes["kVideoLayer"] = 32768] = "kVideoLayer";
        LayerTypes[LayerTypes["kThreeDLayer"] = 65536] = "kThreeDLayer";
    })(LayerTypes || (LayerTypes = {}));
    var LayerTypeUtils = (function () {
        function LayerTypeUtils() {
        }
        LayerTypeUtils.GetlayerType = function (layer) {
            function avLayerType(lObj) {
                var lSource = lObj.source;
                if (lSource instanceof CompItem) {
                    return LayerTypes.kPreCompLayer;
                }
                var lMainSource = lSource.mainSource;
                var lFile = lMainSource.file;
                if (!lObj.hasVideo) {
                    return LayerTypes.kAudioLayer;
                }
                else if (lSource instanceof CompItem) {
                    return LayerTypes.kPreCompLayer;
                }
                else if (lSource.frameDuration < 1) {
                    if (lMainSource instanceof PlaceholderSource) {
                        return LayerTypes.kPlaceholderVideoLayer;
                    }
                    else if (lSource.name.toString().indexOf("].") != -1) {
                        return LayerTypes.kImageSequenceLayer;
                    }
                    else {
                        return LayerTypes.kVideoLayer;
                    }
                }
                else {
                    if (lSource.frameDuration == 1) {
                        if (lMainSource instanceof PlaceholderSource) {
                            return LayerTypes.kPlaceholderStillLayer;
                        }
                        else if (lMainSource.color) {
                            return LayerTypes.kSolidLayer;
                        }
                        else {
                            return LayerTypes.kStillLayer;
                        }
                    }
                }
                return 0;
            }
            try {
                var result = 0;
                var curLayer = layer;
                var instanceOfArray = [AVLayer, CameraLayer, LightLayer, ShapeLayer, TextLayer];
                var instanceOfArrayLength = instanceOfArray.length;
                var avLayer = (LayerTypeUtils.IsBaseAVLayer(curLayer)) ? curLayer : null;
                if (curLayer.nullLayer) {
                    if (avLayer) {
                        return LayerTypes.kNullLayer | (avLayer.threeDLayer ? LayerTypes.kThreeDLayer : 0);
                    }
                    else {
                        return LayerTypes.kNullLayer;
                    }
                }
                else if (avLayer) {
                    if (avLayer.guideLayer) {
                        return LayerTypes.kGuideLayer | (avLayer.threeDLayer ? LayerTypes.kThreeDLayer : 0);
                    }
                    else if (avLayer.adjustmentLayer) {
                        return LayerTypes.kAdjustmentLayer | (avLayer.threeDLayer ? LayerTypes.kThreeDLayer : 0);
                    }
                }
                for (var i = 0; i < instanceOfArrayLength; i += 1) {
                    if (curLayer instanceof instanceOfArray[i]) {
                        result = 1 << i;
                        break;
                    }
                }
                if (result & LayerTypes.kAVLayer) {
                    result |= avLayerType(curLayer);
                    result |= curLayer.threeDLayer ? LayerTypes.kThreeDLayer : 0;
                }
                return result;
            }
            catch (err) {
                alert(err.line.toString + " " + err.toString());
            }
            return 0;
        };
        LayerTypeUtils.IsAVLayer = function (layer) {
            return layer instanceof AVLayer;
        };
        LayerTypeUtils.IsBaseAVLayer = function (layer) {
            return layer instanceof AVLayer || layer instanceof TextLayer || layer instanceof ShapeLayer;
        };
        LayerTypeUtils.GetUIString = function (type) {
            if (type & LayerTypes.kAudioLayer) {
                return "Audio Layer";
            }
            else if (type & LayerTypes.kPreCompLayer) {
                return "PreComp Layer";
            }
            else if (type & LayerTypes.kPlaceholderVideoLayer) {
                return "Placeholder Video Layer";
            }
            else if (type & LayerTypes.kImageSequenceLayer) {
                return "Image Sequence Layer";
            }
            else if (type & LayerTypes.kVideoLayer) {
                return "Video Layer";
            }
            else if (type & LayerTypes.kPlaceholderStillLayer) {
                return "Placeholder Still Layer";
            }
            else if (type & LayerTypes.kSolidLayer) {
                return "Solid Layer";
            }
            else if (type & LayerTypes.kStillLayer) {
                return "Still Layer";
            }
            else if (type & LayerTypes.kGuideLayer) {
                return "Guide Layer";
            }
            else if (type & LayerTypes.kAdjustmentLayer) {
                return "Adjustment Layer";
            }
            else if (type & LayerTypes.kNullLayer) {
                return "Null Layer";
            }
            else if (type & LayerTypes.kAVLayer) {
                return "AV Layer";
            }
            else if (type & LayerTypes.kCameraLayer) {
                return "Camera Layer";
            }
            else if (type & LayerTypes.kLightLayer) {
                return "Light Layer";
            }
            else if (type & LayerTypes.kShapeLayer) {
                return "Shape Layer";
            }
            else if (type & LayerTypes.kTextLayer) {
                return "Text Layer";
            }
            else {
                return "";
            }
        };
        return LayerTypeUtils;
    }());
    var FFUtils = (function () {
        function FFUtils() {
        }
        FFUtils.CalculateBitrate = function (source, factor) {
            factor = Math.max(factor, 0.1);
            return source.width * source.height * source.frameRate * factor / 1024 / 1024;
        };
        FFUtils.GetFFmpegBinary = function () {
            if (Settings.IsMac()) {
                return Settings.BinFolder() + "/ffmpeg_mac/ffmpeg";
            }
            else {
                return Settings.BinFolder() + "/ffmpeg_win/ffmpeg.exe";
            }
        };
        FFUtils.HasBinary = function () {
            var ffpath = FFUtils.GetFFmpegBinary();
            ffpath = ffpath.replace(/\\/g, "\/");
            ffpath = ffpath.replace(/%20/g, "\ ");
            return (new File(ffpath)).exists;
        };
        FFUtils.CreateCommand = function (inputFile, outputFile, extraSetting) {
            if (extraSetting === void 0) { extraSetting = ""; }
            var ffpath = FFUtils.GetFFmpegBinary();
            ffpath = ffpath.replace(/\\/g, "\/");
            ffpath = ffpath.replace(/%20/g, "\ ");
            inputFile = inputFile.replace(/\\/g, "\/");
            outputFile = outputFile.replace(/\\/g, "\/");
            if ((new File(ffpath)).exists && (new File(inputFile)).exists) {
                if (extraSetting.indexOf("-preset") == -1 && extraSetting.indexOf("-b:v") == -1) {
                    extraSetting += " -preset medium";
                }
                return '"' + ffpath + '" -i "' + inputFile + '" ' + extraSetting + ' -vcodec libx264 -pix_fmt yuv420p -bf 0 -y "' + outputFile + '" ';
            }
            else {
                return "";
            }
        };
        FFUtils.CreatePNGSequenceCommans = function (inputFile, outputFolder, outputName) {
            var ffpath = FFUtils.GetFFmpegBinary();
            ffpath = ffpath.replace(/\\/g, "\/");
            ffpath = ffpath.replace(/%20/g, "\ ");
            inputFile = inputFile.replace(/\\/g, "\/");
            outputFolder = outputFolder.replace(/\\/g, "\/");
            var outputPath = outputFolder + "/" + outputName + "_%05d.png";
            if ((new File(ffpath)).exists && (new File(inputFile)).exists) {
                return '"' + ffpath + '" -i "' + inputFile + '" -y "' + outputPath + '" ';
            }
            else {
                return "";
            }
        };
        return FFUtils;
    }());
    var PNGQuantUtil = (function () {
        function PNGQuantUtil() {
        }
        PNGQuantUtil.GetBinary = function () {
            if (Settings.IsMac()) {
                return Settings.BinFolder() + "/pngquant_mac/pngquant";
            }
            else {
                return Settings.BinFolder() + "/pngquant_win/pngquant.exe";
            }
        };
        PNGQuantUtil.HasBinary = function () {
            var ffpath = PNGQuantUtil.GetBinary();
            ffpath = ffpath.replace(/\\/g, "\/");
            ffpath = ffpath.replace(/%20/g, "\ ");
            return (new File(ffpath)).exists;
        };
        PNGQuantUtil.CreateCompressCmdsWithoutFiles = function () {
            var ffpath = PNGQuantUtil.GetBinary();
            ffpath = ffpath.replace(/\\/g, "\/");
            ffpath = ffpath.replace(/%20/g, "\ ");
            return '"' + ffpath + '" --strip --force --speed=1 --quality=50-90 ';
        };
        PNGQuantUtil.CreateCompressCmds = function (inputFile, outputFile) {
            var ffpath = PNGQuantUtil.GetBinary();
            ffpath = ffpath.replace(/\\/g, "\/");
            ffpath = ffpath.replace(/%20/g, "\ ");
            inputFile = inputFile.replace(/\\/g, "\/");
            outputFile = outputFile.replace(/\\/g, "\/");
            return '"' + ffpath + '" --strip --force --speed=1 --quality=50-90 "' + inputFile + '" --output "' + outputFile + '"';
        };
        return PNGQuantUtil;
    }());
    var TransparentVideoHandler = (function () {
        function TransparentVideoHandler() {
        }
        TransparentVideoHandler.FindMp4Extension = function (str) {
            var index = str.lastIndexOf("mp4");
            if (index == str.length - 3) {
                return str.substr(0, str.length - 3);
            }
            else {
                return str;
            }
        };
        TransparentVideoHandler.AddRemoveColorMatte = function (layer) {
            var matte = layer.effect.addProperty("ADBE Remove Color Matting");
            matte.property("ADBE Remove Color Matting-0001").setValue([0, 0, 0, 1]);
        };
        TransparentVideoHandler.CompressNormalVideoStepOne = function (videoFootage, extraSetting) {
            if (extraSetting === void 0) { extraSetting = ""; }
            if (videoFootage.frameRate > 0) {
                var extraSettingLen = extraSetting.length;
                extraSetting = TransparentVideoHandler.FindMp4Extension(extraSetting);
                var exportToMp4 = extraSetting.length < extraSettingLen;
                var smallFilePath = Settings.NewCacheAsset(Settings.NewCacheAssetName(exportToMp4 ? ".mp4" : ".mov"));
                var cmd = FFUtils.CreateCommand(videoFootage.mainSource.file.fsName, smallFilePath, extraSetting);
                var json = new JsonWriter();
                json.startObject();
                json.putKey("cmds");
                json.startArray();
                json.putString(cmd);
                json.endArray();
                json.putKey("output");
                json.putString(smallFilePath);
                json.putKey("replace");
                json.putNumber(videoFootage.id);
                json.endObject();
                return json.getContent();
            }
            return "";
        };
        TransparentVideoHandler.CompressNormalVideoStepTwo = function (cmd) {
            var cmdData = JSON.parse(cmd);
            if (cmdData.output && cmdData.replace) {
                var videoFootage = DomUtils.GetItemById(cmdData.replace);
                var originFile = new File(videoFootage.file.fsName);
                videoFootage.replace(new File(cmdData.output));
                var impOpt = new ImportOptions(originFile);
                app.project.importFile(impOpt);
            }
        };
        TransparentVideoHandler.CompressAlphaVideoStepOne = function (alphaFootage, extraSetting) {
            if (extraSetting === void 0) { extraSetting = ""; }
            if (alphaFootage.frameRate <= 0) {
                return "";
            }
            var extraSettingLen = extraSetting.length;
            extraSetting = TransparentVideoHandler.FindMp4Extension(extraSetting);
            var exportToMp4 = extraSetting.length < extraSettingLen;
            var cmds = [];
            var json = new JsonWriter();
            json.startObject();
            json.putKey("replace");
            json.putNumber(alphaFootage.id);
            var resulComp = app.project.items.addComp(alphaFootage.name, alphaFootage.width, alphaFootage.height, 1, alphaFootage.duration, alphaFootage.frameRate);
            resulComp.bgColor = [0, 0, 0];
            var bgLayer = resulComp.layers.addSolid([0, 0, 0], "BG", alphaFootage.width, alphaFootage.height, 1, alphaFootage.duration);
            bgLayer.moveToEnd();
            var alphaLayer = resulComp.layers.add(alphaFootage);
            var fill = alphaLayer.effect.addProperty("ADBE Fill");
            fill.property("ADBE Fill-0002").setValue([1, 1, 1, 1]);
            var matteFile = Settings.NewCacheAsset(Settings.NewCacheAssetName(".mov"));
            RenderUtils.RenderComp(resulComp, RenderUtils.kNormalVideoRenderTemplate, matteFile);
            fill.remove();
            var matteOutput = Settings.NewCacheAsset(Settings.NewCacheAssetName(exportToMp4 ? ".mp4" : ".mov"));
            json.putKey("matte");
            json.putString(matteOutput);
            cmds.push(FFUtils.CreateCommand(matteFile, matteOutput, extraSetting));
            var solidMatte = alphaLayer.effect.addProperty("ADBE Set Channels");
            solidMatte.property("ADBE Set Channels-0007").setValue(2);
            solidMatte.property("ADBE Set Channels-0008").setValue(4);
            var colorFile = Settings.NewCacheAsset(Settings.NewCacheAssetName(".mov"));
            RenderUtils.RenderComp(resulComp, RenderUtils.kNormalVideoRenderTemplate, colorFile);
            alphaLayer.remove();
            bgLayer.remove();
            var colorOutput = Settings.NewCacheAsset(Settings.NewCacheAssetName(exportToMp4 ? ".mp4" : ".mov"));
            json.putKey("color");
            json.putString(colorOutput);
            cmds.push(FFUtils.CreateCommand(colorFile, colorOutput, extraSetting));
            json.putKey("comp");
            json.putNumber(resulComp.id);
            json.putKey("cmds");
            json.startArray();
            for (var c = 0; c < cmds.length; c++) {
                json.putString(cmds[c]);
            }
            json.endArray();
            json.endObject();
            return json.getContent();
        };
        TransparentVideoHandler.CompressAlphaVideoStepTwo = function (cmd, addRemoveMatteEffect) {
            if (addRemoveMatteEffect === void 0) { addRemoveMatteEffect = true; }
            var cmdData = JSON.parse(cmd);
            if (cmdData.matte && cmdData.color && cmdData.comp && cmdData.replace) {
                var impOpt = new ImportOptions(new File(cmdData.matte));
                var matteFootage = app.project.importFile(impOpt);
                impOpt = new ImportOptions(new File(cmdData.color));
                var colorFootage = app.project.importFile(impOpt);
                var resultComp = DomUtils.GetItemById(cmdData.comp);
                resultComp.width = colorFootage.width;
                resultComp.height = colorFootage.height;
                var colorLayer = resultComp.layers.add(colorFootage);
                colorLayer.anchorPoint.setValue([colorLayer.width * 0.5, colorLayer.height * 0.5, 0]);
                colorLayer.position.setValue([colorLayer.width * 0.5, colorLayer.height * 0.5, 0]);
                colorLayer.trackMatteType = TrackMatteType.LUMA;
                var matteLayer = resultComp.layers.add(matteFootage);
                matteLayer.anchorPoint.setValue([matteLayer.width * 0.5, matteLayer.height * 0.5, 0]);
                matteLayer.position.setValue([matteLayer.width * 0.5, matteLayer.height * 0.5, 0]);
                matteLayer.moveToBeginning();
                matteLayer.enabled = false;
                var videoFootage = DomUtils.GetItemById(cmdData.replace);
                var usedInComps = videoFootage.usedIn;
                for (var c = 0; c < usedInComps.length; c++) {
                    var comp = usedInComps[c];
                    for (var ll = 1; ll <= comp.numLayers; ll++) {
                        var layer = comp.layer(ll);
                        if (layer instanceof AVLayer &&
                            layer.source instanceof FootageItem &&
                            layer.source.id == videoFootage.id &&
                            !LayerMarkerUtils.IsEditableLayer(layer)) {
                            layer.replaceSource(resultComp, true);
                            if (layer.blendingMode == BlendingMode.NORMAL) {
                                layer.collapseTransformation = true;
                            }
                        }
                    }
                }
                return true;
            }
            return false;
        };
        return TransparentVideoHandler;
    }());
    var RenderUtils = (function () {
        function RenderUtils() {
        }
        RenderUtils.GetAllRenderTemplates = function () {
            if (app.project == null) {
                app.newProject();
            }
            var outputModules = [];
            if (app.project.renderQueue.items.length >= 1) {
                for (var i = 0; i < app.project.renderQueue.item(1).outputModules[1].templates.length; i++) {
                    outputModules.push(app.project.renderQueue.item(1).outputModules[1].templates[i]);
                }
            }
            else {
                var tempComp = app.project.items.addComp("temp", 480, 320, 1, 10, 24);
                app.project.renderQueue.items.add(tempComp);
                for (var i = 0; i < app.project.renderQueue.item(1).outputModules[1].templates.length; i++) {
                    outputModules.push(app.project.renderQueue.item(1).outputModules[1].templates[i]);
                }
                app.project.renderQueue.item(1).remove();
                tempComp.remove();
            }
            return outputModules;
        };
        RenderUtils.HasNeededRenderTemplates = function () {
            var needed = [this.kAudioOnlyTemplate, this.kPngFileRenderTemplate, this.kPngSequenceRenderTemplate, this.kStraightAlphaVideoRenderTemplate];
            var modules = this.GetAllRenderTemplates().toString();
            for (var index = 0; index < needed.length; index++) {
                var element = needed[index];
                if (modules.indexOf(element) < 0) {
                    return false;
                }
            }
            return true;
        };
        RenderUtils.InstallRenderTemplates = function () {
            var needed = [this.kAudioOnlyTemplate, this.kPngFileRenderTemplate, this.kPngSequenceRenderTemplate, this.kStraightAlphaVideoRenderTemplate];
            var templateProjFilePath = Settings.BinFolder() + "/ve_dummy.aep";
            var importOption = new ImportOptions(new File(templateProjFilePath));
            var projItem = app.project.importFile(importOption);
            for (var i = 1; i <= app.project.renderQueue.items.length; i++) {
                var outputModule = app.project.renderQueue.item(i).outputModule(1);
                outputModule.saveAsTemplate(outputModule.name);
            }
            projItem.remove();
            app.project.close(CloseOptions.DO_NOT_SAVE_CHANGES);
        };
        RenderUtils.RenderTemplatesCheck = function () {
            if (!this.HasNeededRenderTemplates()) {
                var currentProj = app.project;
                if (currentProj) {
                    alert(VECleaner.kTranslator.mData.HOST_RenderUtils_RenderTemplatesCheck_msg1);
                    currentProj.save();
                    var tempFile = currentProj.file;
                    app.newProject();
                    this.InstallRenderTemplates();
                    if (tempFile != null && typeof tempFile != "undefined") {
                        app.open(tempFile);
                    }
                }
                else {
                    this.InstallRenderTemplates();
                }
            }
        };
        RenderUtils.ClearRenderQueue = function () {
            for (var j = 1; j <= app.project.renderQueue.numItems; ++j) {
                app.project.renderQueue.item(app.project.renderQueue.numItems).remove();
            }
        };
        RenderUtils.RenderComp = function (comp, outputModule, outputPath, startTime, useProxy) {
            if (startTime === void 0) { startTime = 0; }
            if (useProxy === void 0) { useProxy = false; }
            this.ClearRenderQueue();
            var renderQueue = app.project.renderQueue;
            var renderItem = renderQueue.items.add(comp);
            if (outputModule == RenderUtils.kPngFileRenderTemplate) {
                renderItem.timeSpanStart = startTime;
                renderItem.timeSpanDuration = comp.frameDuration;
            }
            else {
                renderItem.timeSpanStart = startTime;
                renderItem.timeSpanDuration = comp.duration;
            }
            renderItem.outputModule(1).applyTemplate(outputModule);
            renderItem.outputModule(1).file = new File(outputPath);
            if (useProxy) {
                renderItem.setSetting("Proxy Use", "Use All Proxies");
            }
            if (renderItem.status == RQItemStatus.QUEUED) {
                renderQueue.render();
                return true;
            }
            else {
                alert(VECleaner.kTranslator.mData.HOST_RenderUtils_RenderComp_msg1 + renderItem.status.toString());
                return false;
            }
        };
        RenderUtils.SaveCompToSingleImage = function (comp, outputPath, renderTime) {
            if (renderTime === void 0) { renderTime = null; }
            if (renderTime == null) {
                var timeRange = TimeRangeUtils.GetVisibleTimeRangeInComp(comp);
                renderTime = timeRange == null ? 0 : timeRange.mInPoint;
            }
            RenderUtils.RenderComp(comp, RenderUtils.kPngFileRenderTemplate, outputPath, renderTime);
            var file = new File(outputPath + '00000');
            var re = /(\S*)\.(\S*)/;
            var nameT = file.displayName.match(re)[1];
            var extention = file.displayName.match(re)[2];
            if (extention != "png") {
                file.rename(nameT + ".png");
            }
        };
        RenderUtils.RenderAndReplaceLayerComp = function (layer, forceVideoOrImage) {
            if (forceVideoOrImage === void 0) { forceVideoOrImage = null; }
            if (layer) {
                var layerTypes = LayerTypeUtils.GetlayerType(layer);
                if (layerTypes & LayerTypes.kPreCompLayer) {
                    var source = layer.source;
                    var impOpt = null;
                    var animated = forceVideoOrImage != null ? forceVideoOrImage : AnimationUtils.DoesCompHasAnimation(source);
                    if (animated) {
                        var newfile = Settings.NewCacheAsset(Settings.NewCacheAssetName(".mov"));
                        RenderUtils.RenderComp(source, RenderUtils.kStraightAlphaVideoRenderTemplate, newfile);
                        impOpt = new ImportOptions(new File(newfile));
                    }
                    else {
                        var newfile = Settings.NewCacheAsset(Settings.NewCacheAssetName(".png"));
                        RenderUtils.SaveCompToSingleImage(source, newfile, Math.abs(layer.inPoint));
                        impOpt = new ImportOptions(new File(newfile));
                    }
                    if (impOpt) {
                        var footage = app.project.importFile(impOpt);
                        layer.replaceSource(footage, true);
                        return true;
                    }
                }
            }
            return false;
        };
        RenderUtils.RenderSelectedLayerAndReplace = function (comp, layers, replace, forceVideoOrImage) {
            if (forceVideoOrImage === void 0) { forceVideoOrImage = null; }
            var result = null;
            var contain = ArrayUtils.DoesArrayContain(layers, replace);
            if (contain) {
                var bgColor = comp.bgColor;
                var parent = replace.parent;
                var shouldEnable = replace.enabled;
                var blendMode = replace.blendingMode;
                comp.bgColor = [0, 0, 0];
                replace.enabled = true;
                replace.blendingMode = BlendingMode.NORMAL;
                var tempLayers = [];
                for (var i = 0; i < layers.length; i++) {
                    tempLayers.push(layers[i]);
                }
                var layerStates = [];
                for (var i = 1; i <= comp.numLayers; i++) {
                    var currentLayer = comp.layer(i);
                    layerStates.push(currentLayer.enabled);
                    if (!ArrayUtils.DoesArrayContain(tempLayers, currentLayer)) {
                        currentLayer.enabled = false;
                        ArrayUtils.RemoveArrayElement(tempLayers, currentLayer);
                    }
                }
                var success = false;
                if (layers.length > 0) {
                    var impOpt = null;
                    var animated = forceVideoOrImage != null ? forceVideoOrImage : AnimationUtils.DoesLayersHaveAnimation(layers);
                    if (animated) {
                        var newfile = Settings.NewCacheAsset(Settings.NewCacheAssetName(".mov"));
                        RenderUtils.RenderComp(comp, RenderUtils.kStraightAlphaVideoRenderTemplate, newfile);
                        impOpt = new ImportOptions(new File(newfile));
                    }
                    else {
                        var newfile = Settings.NewCacheAsset(Settings.NewCacheAssetName(".png"));
                        RenderUtils.SaveCompToSingleImage(comp, newfile);
                        impOpt = new ImportOptions(new File(newfile));
                    }
                    if (impOpt) {
                        success = true;
                        for (var i = 1; i <= comp.numLayers; i++) {
                            comp.layer(i).enabled = layerStates[i - 1];
                        }
                        var footage = app.project.importFile(impOpt);
                        var newLayer = comp.layers.add(footage);
                        newLayer.moveBefore(replace);
                        newLayer.enabled = shouldEnable;
                        newLayer.blendingMode = blendMode;
                        newLayer.parent = (parent);
                        comp.bgColor = bgColor;
                        result = newLayer;
                    }
                }
                if (!success) {
                    for (var i = 1; i <= comp.numLayers; i++) {
                        comp.layer(i).enabled = layerStates[i - 1];
                    }
                }
                else {
                    for (var i = 0; i < layers.length; i++) {
                        if (LayerTypeUtils.IsBaseAVLayer(layers[i])) {
                            layers[i].remove();
                        }
                    }
                }
            }
            return result;
        };
        RenderUtils.IsLayerMaskAnimated = function (layer) {
            if (layer.mask.numProperties > 0) {
                for (var i = 1; i <= layer.mask.numProperties; i++) {
                    var mask = layer.mask.property(i);
                    if (mask.property("ADBE Mask Shape").numKeys > 1) {
                        return true;
                    }
                    if (mask.property("ADBE Mask Feather").numKeys > 1) {
                        return true;
                    }
                    if (mask.property("ADBE Mask Opacity").numKeys > 1) {
                        return true;
                    }
                    if (mask.property("ADBE Mask Offset").numKeys > 1) {
                        return true;
                    }
                }
            }
            return false;
        };
        RenderUtils.CreateCompForTrackMatte = function (layer, matteType) {
            var source = layer.source;
            function createSolidSource(solidColor) {
                var matteComp = app.project.items.addComp(layer.name + "_solid_matte", source.width, source.height, 1, source.duration == 0 ? layer.outPoint - layer.startTime : source.duration, source.frameRate == 0 ? layer.containingComp.frameRate : source.frameRate);
                matteComp.layers.addSolid(solidColor, "color", source.width, source.height, 1, matteComp.duration);
                return matteComp;
            }
            function createMatteLayer(source) {
                var matteLayer = layer.duplicate();
                matteLayer.enabled = true;
                matteLayer.name = layer.name + "_matte_layer";
                matteLayer.moveToBeginning();
                matteLayer.replaceSource(source, true);
                DomUtils.RemoveLayerAllEffects(matteLayer);
                matteLayer.blendingMode = BlendingMode.NORMAL;
                matteLayer.enabled = true;
                return matteLayer;
            }
            switch (matteType) {
                case TrackMatteType.NO_TRACK_MATTE:
                case TrackMatteType.ALPHA: {
                    var matteLayer = createMatteLayer(createSolidSource([1, 1, 1]));
                    var result = matteLayer.containingComp.layers.precompose([matteLayer.index], matteLayer.name, true);
                    return result;
                }
                case TrackMatteType.ALPHA_INVERTED: {
                    var matteLayer1 = createMatteLayer(createSolidSource([1, 1, 1]));
                    var effect1 = matteLayer1.effect.addProperty("ADBE Invert");
                    effect1.property("ADBE Invert-0001").setValue(16);
                    var result = matteLayer1.containingComp.layers.precompose([matteLayer1.index], matteLayer1.name, true);
                    return result;
                }
                case TrackMatteType.LUMA: {
                    var matteLayer2 = createMatteLayer(createSolidSource([1, 1, 1]));
                    var result = matteLayer2.containingComp.layers.precompose([matteLayer2.index], matteLayer2.name, true);
                    result.layers.addSolid([0, 0, 0], "bg", result.width, result.height, 1, result.duration).moveToEnd();
                    return result;
                }
                case TrackMatteType.LUMA_INVERTED: {
                    var matteLayer2 = createMatteLayer(createSolidSource([0, 0, 0]));
                    var result = matteLayer2.containingComp.layers.precompose([matteLayer2.index], matteLayer2.name, true);
                    result.layers.addSolid([1, 1, 1], "bg", result.width, result.height, 1, result.duration).moveToEnd();
                    return result;
                }
            }
        };
        RenderUtils.ProcessLayerMasks = function (layer) {
            function DoesMaskSupported() {
                if (layer.mask.numProperties > 0) {
                    for (var m = 1; m <= layer.mask.numProperties; m++) {
                        var mask = layer.mask.property(m);
                        var feather = mask.property("ADBE Mask Feather");
                        var featherValue = feather.valueAtTime(0, false);
                        if (feather.numKeys > 0 || featherValue[0] != 0 || featherValue[1] != 0) {
                            return false;
                        }
                        var opacity = mask.property("ADBE Mask Opacity");
                        var opacityValue = opacity.valueAtTime(0, false);
                        if (opacity.numKeys > 0 || opacityValue != 100) {
                            return false;
                        }
                        var expansion = mask.property("ADBE Mask Offset");
                        var expansionValue = expansion.valueAtTime(0, false);
                        if (expansion.numKeys > 0 || expansionValue != 0) {
                            return false;
                        }
                        var maskMode = mask.maskMode;
                        if (maskMode == MaskMode.DARKEN || maskMode == MaskMode.LIGHTEN) {
                            return false;
                        }
                        if (mask.inverted) {
                            return false;
                        }
                    }
                }
                return true;
            }
            if (!DoesMaskSupported()) {
                CompCleaner.ClearSelection(layer.containingComp);
                if (!LayerMarkerUtils.DoesLayerIsOrContainsEditableLayer(layer)) {
                    var idx = layer.index;
                    var parent = layer.containingComp;
                    var comp = parent.layers.precompose([idx], layer.name, false);
                    parent.openInViewer();
                    layer = parent.layer(idx);
                    layer.selected = false;
                    layer.mask.selected = true;
                    app.executeCommand(19);
                    layer.mask.selected = false;
                    layer.selected = false;
                    comp.openInViewer();
                    comp.layer(1).selected = true;
                    app.executeCommand(20);
                    DomUtils.RemoveLayerAllMasks(layer);
                    RenderUtils.RenderAndReplaceLayerComp(layer);
                }
                else {
                    RenderUtils.CreateCompForTrackMatte(layer, layer.trackMatteType);
                    DomUtils.RemoveLayerAllMasks(layer);
                    var matteLayer = layer.containingComp.layer(1);
                    if (layer.trackMatteType == TrackMatteType.NO_TRACK_MATTE) {
                        matteLayer = RenderUtils.RenderSelectedLayerAndReplace(layer.containingComp, [matteLayer], matteLayer, RenderUtils.IsLayerMaskAnimated(matteLayer));
                        matteLayer.moveBefore(layer);
                        layer.trackMatteType = TrackMatteType.ALPHA;
                    }
                    else {
                        matteLayer = RenderUtils.RenderSelectedLayerAndReplace(layer.containingComp, [matteLayer], matteLayer, RenderUtils.IsLayerMaskAnimated(matteLayer));
                        matteLayer.moveBefore(layer);
                        matteLayer.trackMatteType = layer.trackMatteType;
                        layer.containingComp.layers.precompose([matteLayer.index, matteLayer.index - 1], layer.name + "_matte", true);
                    }
                    layer.containingComp.layer(layer.index - 1).enabled = false;
                }
                return true;
            }
            return false;
        };
        RenderUtils.ProcessCompMasks = function (comp, root) {
            for (var i = 1; i <= comp.numLayers; i++) {
                var layer = comp.layer(i);
                if (LayerTypeUtils.IsBaseAVLayer(layer)) {
                    RenderUtils.ProcessLayerMasks(layer);
                }
            }
        };
        RenderUtils.kAudioOnlyTemplate = "VE_AUDIO_ONLY";
        RenderUtils.kPngFileRenderTemplate = "VE_PNG_SINGLE";
        RenderUtils.kPngSequenceRenderTemplate = "VE_PNG_SEQUENCE";
        RenderUtils.kNormalVideoRenderTemplate = "VE_NORMAL_VIDEO";
        RenderUtils.kAlphaVideoRenderTemplate = "VE_ALPHA_VIDEO";
        RenderUtils.kStraightAlphaVideoRenderTemplate = "VE_STRAIGHT_ALPHA_VIDEO";
        return RenderUtils;
    }());
    var PreCompUtils = (function () {
        function PreCompUtils() {
        }
        PreCompUtils.PrecomposeAndAdjustDuraion = function (layers, parent, name) {
            if (name === void 0) { name = ""; }
            if (layers.length > 0 && parent) {
                var parentLayer = layers.length == 1 ? layers[0].parent : null;
                var myLayers = [];
                for (var l = 0; l < layers.length; l++) {
                    myLayers.push(layers[l].index);
                }
                var precompIndices = myLayers;
                var precompName = name.length == 0 ? "Precomp_" + layers[0].name : name;
                var parentComp = parent;
                var Inpoint = 0;
                var Outpoint = 0;
                var precomp = parentComp.layers.precompose(precompIndices, precompName, true);
                var adjustStartTime = precomp.duration, newCompDuration = 0;
                for (var i = 1; i <= precomp.layers.length; i++) {
                    var layer = precomp.layer(i);
                    Inpoint = (Inpoint > layer.inPoint) ? layer.inPoint : Inpoint;
                    Outpoint = (Outpoint < layer.outPoint) ? layer.outPoint : Outpoint;
                    var duration = Outpoint - Inpoint;
                    adjustStartTime = adjustStartTime > layer.inPoint ? layer.inPoint : adjustStartTime;
                    newCompDuration = newCompDuration < duration ? duration : newCompDuration;
                }
                for (var i = 1; i <= precomp.layers.length; i++) {
                    precomp.layer(i).startTime -= adjustStartTime;
                }
                precomp.duration = newCompDuration;
                var precompLayer = parentComp.layer(precompName);
                precompLayer.startTime = adjustStartTime;
                precompLayer.parent = (parentLayer);
                return precompLayer;
            }
            return null;
        };
        return PreCompUtils;
    }());
    var TimeRange = (function () {
        function TimeRange(inPoint, outPoint) {
            if (inPoint === void 0) { inPoint = 0; }
            if (outPoint === void 0) { outPoint = 0; }
            this.mInPoint = inPoint;
            this.mOutPoint = outPoint;
        }
        TimeRange.prototype.setFromLayer = function (layer) {
            this.mInPoint = layer.inPoint;
            this.mOutPoint = layer.outPoint;
        };
        TimeRange.prototype.offset = function (offset) {
            this.mInPoint += offset;
            this.mOutPoint += offset;
        };
        TimeRange.prototype.inRange = function (time) {
            return time >= this.mInPoint && this.mOutPoint;
        };
        TimeRange.prototype.isOverlap = function (other) {
            return this.inRange(other.mInPoint) || this.inRange(other.mOutPoint);
        };
        TimeRange.prototype.getOverlapped = function (other) {
            if (other != null && this.isOverlap(other)) {
                return new TimeRange(Math.max(this.mInPoint, other.mInPoint), Math.min(this.mOutPoint, other.mOutPoint));
            }
            else if (other == null) {
                return new TimeRange(this.mInPoint, this.mOutPoint);
            }
            return null;
        };
        return TimeRange;
    }());
    var TimeRangeUtils = (function () {
        function TimeRangeUtils() {
        }
        TimeRangeUtils.GetOverlappedTimeRangeForLayers = function (layers) {
            function getLayerTimeRange(layer) {
                var tmp = new TimeRange();
                if (layer instanceof AVLayer && layer.source instanceof CompItem) {
                    tmp = TimeRangeUtils.GetOverlappedTimeRangeForAllLayersInComp(layer.source, true);
                    if (tmp) {
                        tmp.offset(layer.startTime);
                    }
                }
                else {
                    tmp.setFromLayer(layer);
                }
                return tmp;
            }
            var timeRange = null;
            if (layers.length > 0) {
                timeRange = getLayerTimeRange(layers[0]);
                for (var l = 1; l < layers.length; l++) {
                    var tmp = getLayerTimeRange(layers[l]);
                    timeRange = timeRange.getOverlapped(tmp);
                    if (timeRange == null) {
                        return null;
                    }
                }
            }
            return timeRange;
        };
        TimeRangeUtils.GetOverlappedTimeRangeForAllLayersInComp = function (comp, filterAVLayer) {
            var layers = [];
            for (var i = 1; i <= comp.numLayers; i++) {
                if (filterAVLayer && LayerTypeUtils.IsBaseAVLayer(comp.layer(i)) && comp.layer(i).enabled) {
                    layers.push(comp.layer(i));
                }
                else if (!filterAVLayer) {
                    layers.push(comp.layer(i));
                }
            }
            return TimeRangeUtils.GetOverlappedTimeRangeForLayers(layers);
        };
        TimeRangeUtils.GetVisibleTimeRangeInComp = function (comp) {
            return TimeRangeUtils.GetOverlappedTimeRangeForAllLayersInComp(comp, true);
        };
        return TimeRangeUtils;
    }());
    var AnimationUtils = (function () {
        function AnimationUtils() {
        }
        AnimationUtils.DoesPropertyHasAnimation = function (prop) {
            if (prop.propertyType == PropertyType.PROPERTY) {
                var property = prop;
                if (property.numKeys > 1 || (property.expression != "" && property.expressionEnabled)) {
                    return true;
                }
            }
            else {
                for (var i = prop.numProperties; i > 0; i--) {
                    if (AnimationUtils.DoesPropertyHasAnimation(prop.property(i))) {
                        return true;
                    }
                }
            }
            return false;
        };
        AnimationUtils.DoesLayerHasAnimation = function (layer) {
            var hasAnimation = false;
            var layerTypes = LayerTypeUtils.GetlayerType(layer);
            if (layerTypes & LayerTypes.kAVLayer) {
                if ((layerTypes & LayerTypes.kImageSequenceLayer || layerTypes & LayerTypes.kVideoLayer)) {
                    hasAnimation = true;
                }
                else if (layerTypes & LayerTypes.kPreCompLayer) {
                    hasAnimation = AnimationUtils.DoesCompHasAnimation(layer.source);
                }
            }
            if (!hasAnimation) {
                for (var k = 1; k <= layer.numProperties; k += 1) {
                    if (AnimationUtils.DoesPropertyHasAnimation(layer.property(k))) {
                        return true;
                    }
                }
            }
            return hasAnimation;
        };
        AnimationUtils.DoesCompHasAnimation = function (comp) {
            var numLayers = comp.numLayers;
            for (var i = 1; i <= numLayers; i++) {
                if (AnimationUtils.DoesLayerHasAnimation(comp.layer(i))) {
                    return true;
                }
            }
            if (numLayers > 1) {
                return TimeRangeUtils.GetOverlappedTimeRangeForAllLayersInComp(comp, false) != null;
            }
            return false;
        };
        AnimationUtils.DoesLayersHaveAnimation = function (layers) {
            for (var i = 0; i < layers.length; i++) {
                if (AnimationUtils.DoesLayerHasAnimation(layers[i])) {
                    return true;
                }
            }
            return TimeRangeUtils.GetOverlappedTimeRangeForLayers(layers) != null;
        };
        AnimationUtils.RemovePropertyAnimation = function (prop) {
            if (prop.propertyType == PropertyType.PROPERTY) {
                var property = prop;
                while (property.numKeys > 0) {
                    property.removeKey(1);
                }
                if (property.expressionEnabled && property.canSetExpression) {
                    property.expression = "";
                }
            }
            else {
                for (var i = prop.numProperties; i > 0; i--) {
                    AnimationUtils.RemovePropertyAnimation(prop.property(i));
                }
            }
        };
        AnimationUtils.RemoveLayerAnimation = function (layer) {
            for (var k = 1; k <= layer.numProperties; k += 1) {
                AnimationUtils.RemovePropertyAnimation(layer.property(k));
            }
        };
        AnimationUtils.CopyPropertyAnimation = function (fromProp, toProp) {
            AnimationUtils.RemovePropertyAnimation(toProp);
            for (var k = 1; k <= fromProp.numKeys; k++) {
                toProp.addKey(fromProp.keyTime(k));
                toProp.setValueAtKey(k, fromProp.keyValue(k));
            }
            if (fromProp.expressionEnabled && fromProp.canSetExpression && toProp.canSetExpression) {
                toProp.expression = fromProp.expression;
                toProp.expressionEnabled = fromProp.expressionEnabled;
            }
        };
        return AnimationUtils;
    }());
    var EditableType;
    (function (EditableType) {
        EditableType[EditableType["kNone"] = 0] = "kNone";
        EditableType[EditableType["kImageSource"] = 1] = "kImageSource";
        EditableType[EditableType["kTextSource"] = 2] = "kTextSource";
    })(EditableType || (EditableType = {}));
    var TypeMarkerInfo = (function () {
        function TypeMarkerInfo(layer, marker) {
            this.mType = EditableType.kNone;
            this.mGroup = null;
            this.mInnerGroupIndex = null;
            this.mLayer = layer;
            this.mValid = false;
            this.mType = EditableType.kNone;
            this.mContent = marker;
            this.mValid = this.parse();
        }
        TypeMarkerInfo.prototype.parse = function () {
            if (this.mContent.length > 0) {
                var ret = JSON.parse(this.mContent);
                if (ret != null) {
                    var type = ret[TypeMarkerInfo.kEditableType];
                    if (typeof (type) == "number") {
                        this.mType = type;
                        var group = ret[TypeMarkerInfo.kEditorGroup];
                        if (typeof (group) == "number") {
                            this.mGroup = group;
                        }
                        var innerGroupIndex = ret[TypeMarkerInfo.kEditorInnerGroupIndex];
                        if (typeof (innerGroupIndex) == "number") {
                            this.mInnerGroupIndex = innerGroupIndex;
                        }
                        return true;
                    }
                }
                else if (LayerTypeUtils.IsBaseAVLayer(this.mLayer)) {
                    if (LayerMarkerUtils.CheckLayerMarkerForValue(this.mLayer, LayerMarkerUtils.kEditableImage)) {
                        this.mType = EditableType.kImageSource;
                        return true;
                    }
                    else if (this.mLayer instanceof TextLayer && LayerMarkerUtils.CheckLayerMarkerForValue(this.mLayer, LayerMarkerUtils.kEditableText)) {
                        this.mType = EditableType.kTextSource;
                        return true;
                    }
                }
            }
            return false;
        };
        TypeMarkerInfo.prototype.setGroup = function (group) {
            if (group >= 1) {
                this.mGroup = group;
            }
            else {
                this.mGroup = null;
            }
        };
        TypeMarkerInfo.prototype.setInnerGroupIndex = function (index) {
            this.mInnerGroupIndex = index;
        };
        TypeMarkerInfo.prototype.getContent = function () {
            if (this.mValid) {
                var json = new JsonWriter();
                json.startObject();
                json.putKey(TypeMarkerInfo.kEditableType);
                json.putNumber(this.mType);
                if (typeof (this.mGroup) == "number") {
                    json.putKey(TypeMarkerInfo.kEditorGroup);
                    json.putNumber(this.mGroup);
                    if (typeof (this.mInnerGroupIndex) == "number") {
                        json.putKey(TypeMarkerInfo.kEditorInnerGroupIndex);
                        json.putNumber(this.mInnerGroupIndex);
                    }
                }
                json.endObject();
                return json.getContent();
            }
            return "";
        };
        TypeMarkerInfo.prototype.removeFromLayer = function () {
            LayerMarkerUtils.ClearLayerMarkers(this.mLayer);
        };
        TypeMarkerInfo.prototype.updateToLayer = function () {
            LayerMarkerUtils.AddMarkerToLayer(this.mLayer, this.getContent(), this.mLayer.inPoint);
        };
        TypeMarkerInfo.kEditableType = "VE_EDITABLE_TYPE";
        TypeMarkerInfo.kEditorGroup = "VE_GROUP";
        TypeMarkerInfo.kEditorInnerGroupIndex = "VE_GROUP_INDEX";
        return TypeMarkerInfo;
    }());
    var GroupTimeStampInfo = (function () {
        function GroupTimeStampInfo(content, layer) {
            this.mLayer = layer;
            this.mContent = content;
            this.mValid = this.parse();
        }
        GroupTimeStampInfo.prototype.parse = function () {
            if (this.mContent != null && this.mContent.length > 0) {
                var ret = JSON.parse(this.mContent);
                if (ret != null) {
                    var group = ret[GroupTimeStampInfo.kEditorGroup];
                    if (typeof (group) == "number") {
                        var time = ret[GroupTimeStampInfo.kEditorGroupTimeStamp];
                        if (typeof (time) == "number") {
                            this.mGroup = group;
                            this.mTimeStamp = parseFloat(time.toFixed(2));
                            return true;
                        }
                    }
                }
            }
            return false;
        };
        GroupTimeStampInfo.prototype.setGroup = function (group) {
            this.mGroup = group;
            if (this.mGroup != null && this.mTimeStamp != null) {
                this.mValid = true;
            }
        };
        GroupTimeStampInfo.prototype.setGroupTimeStamp = function (time) {
            this.mTimeStamp = parseFloat(time.toFixed(2));
            if (this.mGroup != null && this.mTimeStamp != null) {
                this.mValid = true;
            }
        };
        GroupTimeStampInfo.prototype.getContent = function () {
            if (typeof (this.mGroup) == "number" && typeof (this.mTimeStamp) == "number") {
                var json = new JsonWriter();
                json.startObject();
                json.putKey(GroupTimeStampInfo.kEditorGroup);
                json.putNumber(this.mGroup);
                json.putKey(GroupTimeStampInfo.kEditorGroupTimeStamp);
                json.putNumber(this.mTimeStamp);
                json.endObject();
                this.mContent = json.getContent();
                return this.mContent;
            }
            return "";
        };
        GroupTimeStampInfo.prototype.removeFromLayer = function () {
            if (this.mLayer && this.mValid) {
                var numKeys = this.mLayer.marker.numKeys;
                for (var i = 0; i < numKeys; i++) {
                    var marker = this.mLayer.marker.keyValue(i + 1);
                    if (marker.comment == this.mContent) {
                        this.mLayer.marker.removeKey(i + 1);
                        return;
                    }
                }
            }
        };
        GroupTimeStampInfo.prototype.updateToLayer = function () {
            var content = this.getContent();
            if (content.length > 0) {
                LayerMarkerUtils.AddMarkerToLayer(this.mLayer, this.getContent(), this.mTimeStamp);
            }
        };
        GroupTimeStampInfo.prototype.toJson = function (writer) {
            if (this.mValid) {
                writer.startObject();
                writer.putKey("group");
                writer.putNumber(this.mGroup);
                writer.putKey("time");
                writer.putNumber(this.mTimeStamp);
                writer.endObject();
            }
        };
        GroupTimeStampInfo.kEditorGroup = "VE_GROUP";
        GroupTimeStampInfo.kEditorGroupTimeStamp = "VE_GROUP_TIME_STAMP";
        return GroupTimeStampInfo;
    }());
    var LayerMarkerUtils = (function () {
        function LayerMarkerUtils() {
        }
        LayerMarkerUtils.AddMarkerToLayer = function (layer, value, time) {
            if (layer) {
                this.RemoveLayerMarkerAtTime(layer, time);
                layer.marker.setValueAtTime(time, new MarkerValue(value));
            }
        };
        LayerMarkerUtils.AddEditableImageMarker = function (layer) {
            if (!this.IsEditableImageLayer(layer)) {
                this.AddMarkerToLayer(layer, this.kEditableImage, layer.inPoint);
            }
        };
        LayerMarkerUtils.AddEditableTextMarker = function (text) {
            if (!this.IsEditableTextLayer(text)) {
                this.AddMarkerToLayer(text, this.kEditableText, text.inPoint);
            }
        };
        LayerMarkerUtils.CheckLayerMarkerForValue = function (layer, value) {
            var numKeys = layer.marker.numKeys;
            for (var i = 0; i < numKeys; i++) {
                var marker = layer.marker.keyValue(i + 1);
                if (marker.comment.indexOf(value) > -1) {
                    return true;
                }
            }
            return false;
        };
        LayerMarkerUtils.CheckLayerMarkerForType = function (layer, type) {
            var numKeys = layer.marker.numKeys;
            for (var i = 0; i < numKeys; i++) {
                var marker = layer.marker.keyValue(i + 1);
                var info = new TypeMarkerInfo(layer, marker.comment);
                if (info.mValid && info.mType === type) {
                    return true;
                }
            }
            return false;
        };
        LayerMarkerUtils.IsEditableImageLayer = function (layer) {
            return this.CheckLayerMarkerForType(layer, EditableType.kImageSource);
        };
        LayerMarkerUtils.IsEditableTextLayer = function (layer) {
            return this.CheckLayerMarkerForType(layer, EditableType.kTextSource);
        };
        LayerMarkerUtils.IsEditableLayer = function (layer) {
            if (LayerTypeUtils.IsBaseAVLayer(layer)) {
                if (layer instanceof TextLayer && LayerMarkerUtils.IsEditableTextLayer(layer)) {
                    return true;
                }
                else {
                    if (LayerMarkerUtils.IsEditableImageLayer(layer)) {
                        return true;
                    }
                }
            }
            return false;
        };
        LayerMarkerUtils.GetLayerTypeMarkerInfo = function (layer) {
            var numKeys = layer.marker.numKeys;
            for (var i = 0; i < numKeys; i++) {
                var marker = layer.marker.keyValue(i + 1);
                var info = new TypeMarkerInfo(layer, marker.comment);
                if (info.mValid) {
                    return info;
                }
            }
            return null;
        };
        LayerMarkerUtils.DoesCompHasEditableLayers = function (comp) {
            for (var i = 1, l = comp.numLayers; i <= l; i++) {
                var layer = comp.layer(i);
                if (LayerTypeUtils.IsBaseAVLayer(layer)) {
                    if (layer instanceof TextLayer && LayerMarkerUtils.IsEditableTextLayer(layer)) {
                        return true;
                    }
                    else {
                        if (LayerMarkerUtils.IsEditableImageLayer(comp.layer(i))) {
                            return true;
                        }
                        var layerTypes = LayerTypeUtils.GetlayerType(layer);
                        if (layerTypes & LayerTypes.kPreCompLayer) {
                            var source = layer.source;
                            if (LayerMarkerUtils.DoesCompHasEditableLayers(source)) {
                                return true;
                            }
                        }
                    }
                }
            }
            return false;
        };
        LayerMarkerUtils.DoesLayerIsOrContainsEditableLayer = function (layer) {
            if (layer instanceof TextLayer) {
                return LayerMarkerUtils.IsEditableTextLayer(layer);
            }
            else {
                if (LayerMarkerUtils.IsEditableImageLayer(layer)) {
                    return true;
                }
                var layerTypes = LayerTypeUtils.GetlayerType(layer);
                if (layerTypes & LayerTypes.kPreCompLayer) {
                    var source = layer.source;
                    return LayerMarkerUtils.DoesCompHasEditableLayers(source);
                }
            }
            return false;
        };
        LayerMarkerUtils.RemoveLayerMarkerAtTime = function (layer, time) {
            var numKeys = layer.marker.numKeys;
            for (var i = 0; i < numKeys; i++) {
                if (time == layer.marker.keyTime(i + 1)) {
                    layer.marker.removeKey(i + 1);
                }
            }
        };
        LayerMarkerUtils.ClearLayerMarkers = function (layer) {
            while (layer.marker.numKeys > 0) {
                layer.marker.removeKey(1);
            }
        };
        LayerMarkerUtils.kEditableImage = "VE_EDITABLE_IMAGE";
        LayerMarkerUtils.kEditableText = "VE_EDITABLE_TEXT";
        return LayerMarkerUtils;
    }());
    var GroupTimeStampHandler = (function () {
        function GroupTimeStampHandler(comp) {
            this.mMainComp = comp;
            this.loadAllStamp();
        }
        GroupTimeStampHandler.GetDefaultTimeStampHandler = function () {
            var items = app.project.items;
            for (var i = 1; i <= items.length; i++) {
                var item = app.project.item(i);
                if (item instanceof CompItem) {
                    for (var l = 1; l <= item.numLayers; l++) {
                        var layer = item.layer(l);
                        if (layer instanceof AVLayer && layer.guideLayer && layer.name == GroupTimeStampHandler.kStampLayerName) {
                            return new GroupTimeStampHandler(item);
                        }
                    }
                }
            }
            return null;
        };
        GroupTimeStampHandler.prototype.getStampLayer = function (create) {
            if (this.mMainComp) {
                for (var l = 1; l <= this.mMainComp.numLayers; l++) {
                    var layer = this.mMainComp.layer(l);
                    if (layer instanceof AVLayer && layer.guideLayer && layer.name == GroupTimeStampHandler.kStampLayerName) {
                        return layer;
                    }
                }
                if (create) {
                    var layer = this.mMainComp.layers.addNull(this.mMainComp.duration);
                    layer.enabled = false;
                    layer.shy = true;
                    layer.name = GroupTimeStampHandler.kStampLayerName;
                    layer.guideLayer = true;
                    return layer;
                }
            }
            return null;
        };
        GroupTimeStampHandler.prototype.loadAllStamp = function () {
            this.mTimeStamps = [];
            var layer = this.getStampLayer(false);
            if (layer) {
                var numKeys = layer.marker.numKeys;
                for (var i = 0; i < numKeys; i++) {
                    var marker = layer.marker.keyValue(i + 1);
                    var info = new GroupTimeStampInfo(marker.comment, layer);
                    if (info.mValid) {
                        this.mTimeStamps.push(info);
                    }
                }
            }
        };
        GroupTimeStampHandler.prototype.getStampForGroup = function (group) {
            for (var i = 0; i < this.mTimeStamps.length; i++) {
                if (this.mTimeStamps[i].mGroup == group) {
                    return this.mTimeStamps[i];
                }
            }
            return null;
        };
        GroupTimeStampHandler.prototype.removeStampForGroup = function (group) {
            var stamp = this.getStampForGroup(group);
            if (stamp) {
                stamp.removeFromLayer();
                ArrayUtils.RemoveArrayElement(this.mTimeStamps, stamp);
            }
        };
        GroupTimeStampHandler.prototype.addStampForGroup = function (group) {
            if (this.mMainComp) {
                this.removeStampForGroup(group);
                var time = this.mMainComp.time;
                var layer = this.getStampLayer(true);
                var info = new GroupTimeStampInfo("", layer);
                info.setGroup(group);
                info.setGroupTimeStamp(time);
                info.updateToLayer();
                this.loadAllStamp();
            }
        };
        GroupTimeStampHandler.prototype.changeStampGroupTo = function (from, to) {
            var stamp = this.getStampForGroup(from);
            if (stamp) {
                stamp.setGroup(to);
                stamp.updateToLayer();
            }
        };
        GroupTimeStampHandler.prototype.removeAll = function () {
            for (var i = 0; i < this.mTimeStamps.length; i++) {
                this.mTimeStamps[i].removeFromLayer();
            }
        };
        GroupTimeStampHandler.prototype.exportGroupTimeStampInfo = function () {
            if (this.mMainComp != null && this.mTimeStamps.length > 0) {
                var writer = new JsonWriter();
                writer.startArray();
                for (var index = 0; index < this.mTimeStamps.length; index++) {
                    var timeStamp = this.mTimeStamps[index];
                    timeStamp.toJson(writer);
                }
                writer.endArray();
                return writer.getContent();
            }
            return "";
        };
        GroupTimeStampHandler.kStampLayerName = "VE_TIMESTAMP_LAYER";
        return GroupTimeStampHandler;
    }());
    var EditableLayerHandler = (function () {
        function EditableLayerHandler() {
            this.mGroupedEditableLayers = [];
            this.update();
        }
        EditableLayerHandler.prototype.update = function () {
            this.mGroupedEditableLayers = [];
            this.mOtherEditableLayer = [];
            var finished = [];
            for (var i = 1; i <= app.project.numItems; i++) {
                if (app.project.item(i) instanceof CompItem) {
                    this.loadEditableLayers(app.project.item(i), finished);
                }
            }
            this.removeEmptyGroups();
        };
        EditableLayerHandler.prototype.loadEditableLayers = function (comp, finished) {
            for (var i = 0; i < finished.length; i++) {
                if (finished[i] == comp.id) {
                    return;
                }
            }
            finished.push(comp.id);
            for (var i = 1; i <= comp.numLayers; i++) {
                var layer = comp.layer(i);
                if (LayerTypeUtils.IsBaseAVLayer(layer)) {
                    if (layer.source instanceof CompItem) {
                        this.loadEditableLayers(layer.source, finished);
                    }
                    else {
                        var asset = LayerMarkerUtils.GetLayerTypeMarkerInfo(layer);
                        if (asset) {
                            if (asset.mGroup == null) {
                                this.mOtherEditableLayer.push(asset);
                            }
                            else {
                                var group = this.getGroup(asset.mGroup - 1);
                                this.addAssetToGroup(group, asset);
                            }
                        }
                    }
                }
            }
        };
        EditableLayerHandler.prototype.removeEmptyGroups = function () {
            for (var g = 0; g < this.mGroupedEditableLayers.length; g++) {
                var group = this.mGroupedEditableLayers[g];
                if (group.length == 0) {
                    for (var gg = g + 1; gg < this.mGroupedEditableLayers.length; gg++) {
                        var group2 = this.mGroupedEditableLayers[gg];
                        for (var l = 0; l < group2.length; l++) {
                            var layer = group2[l];
                            layer.setGroup(layer.mGroup - 1);
                            layer.updateToLayer();
                        }
                    }
                    ArrayUtils.RemoveArrayElement(this.mGroupedEditableLayers, group);
                    g--;
                }
            }
        };
        EditableLayerHandler.prototype.getGroup = function (index) {
            if (index >= this.mGroupedEditableLayers.length) {
                for (var i = this.mGroupedEditableLayers.length; i <= index; i++) {
                    this.mGroupedEditableLayers.push([]);
                }
            }
            return this.mGroupedEditableLayers[index];
        };
        EditableLayerHandler.prototype.addAssetToGroup = function (group, asset) {
            if (asset.mInnerGroupIndex == null) {
                asset.setInnerGroupIndex(group.length);
                group.push(asset);
            }
            else {
                if (asset.mInnerGroupIndex >= group.length) {
                    for (var i = group.length; i < asset.mInnerGroupIndex; i++) {
                        group.push(null);
                    }
                    group.push(asset);
                }
                else {
                    group[asset.mInnerGroupIndex] = asset;
                }
            }
        };
        EditableLayerHandler.prototype.moveGroupUp = function (index) {
            index = index - 1;
            if (index > 0 && index < this.mGroupedEditableLayers.length) {
                var upper = this.mGroupedEditableLayers[index - 1];
                for (var i = 0; i < upper.length; i++) {
                    upper[i].setGroup(upper[i].mGroup + 1);
                    upper[i].updateToLayer();
                }
                var current = this.mGroupedEditableLayers[index];
                for (var i = 0; i < current.length; i++) {
                    current[i].setGroup(current[i].mGroup - 1);
                    current[i].updateToLayer();
                }
                return true;
            }
            return false;
        };
        EditableLayerHandler.prototype.moveGroupDown = function (index) {
            index = index - 1;
            if (index >= 0 && index < this.mGroupedEditableLayers.length - 1) {
                var lower = this.mGroupedEditableLayers[index + 1];
                for (var i = 0; i < lower.length; i++) {
                    lower[i].setGroup(lower[i].mGroup - 1);
                    lower[i].updateToLayer();
                }
                var current = this.mGroupedEditableLayers[index];
                for (var i = 0; i < current.length; i++) {
                    current[i].setGroup(current[i].mGroup + 1);
                    current[i].updateToLayer();
                }
                return true;
            }
            return false;
        };
        EditableLayerHandler.prototype.makeGroupFromLayers = function (indices) {
            var groupIndex = this.mGroupedEditableLayers.length + 1;
            var layers = [];
            for (var i = 0; i < indices.length; i++) {
                var ll = this.mOtherEditableLayer[indices[i] - 1];
                ll.setGroup(groupIndex);
                ll.setInnerGroupIndex(i);
                layers.push(ll);
                ll.updateToLayer();
            }
            this.update();
        };
        EditableLayerHandler.prototype.releaseGroup = function (index) {
            if (index > 0 && index <= this.mGroupedEditableLayers.length) {
                for (var g = index; g < this.mGroupedEditableLayers.length; g++) {
                    var group_1 = this.mGroupedEditableLayers[g];
                    for (var l = 0; l < group_1.length; l++) {
                        group_1[l].setGroup(g);
                        group_1[l].updateToLayer();
                    }
                }
                var group = this.mGroupedEditableLayers[index - 1];
                for (var l = 0; l < group.length; l++) {
                    group[l].setGroup(0);
                    group[l].updateToLayer();
                }
                this.update();
            }
        };
        return EditableLayerHandler;
    }());
    var ExpressionHandlerUtils = (function () {
        function ExpressionHandlerUtils() {
        }
        ExpressionHandlerUtils.IsExpressionControl = function (name) {
            for (var index = 0; index < ExpressionHandlerUtils.kExpressionControlEffects.length; index++) {
                var element = ExpressionHandlerUtils.kExpressionControlEffects[index];
                if (element == name) {
                    return true;
                }
            }
            return false;
        };
        ExpressionHandlerUtils.RemoveLayerExpressionControlEffects = function (layer) {
            for (var i = 1; i <= layer.effect.numProperties; i++) {
                if (ExpressionHandlerUtils.IsExpressionControl(layer.effect.property(i).matchName)) {
                    layer.effect.property(i).remove();
                    i--;
                }
            }
            if (layer.collapseTransformation && layer.effect.numProperties == 0 && layer.source instanceof CompItem) {
                layer.collapseTransformation = false;
            }
        };
        ExpressionHandlerUtils.ConvertPropertyExpressionToKeyframes = function (theProperty) {
            if (theProperty.expression !== "" && theProperty.expressionEnabled) {
                theProperty.selected = true;
                app.executeCommand(2639);
                theProperty.selected = false;
                theProperty.expression = "";
            }
        };
        ExpressionHandlerUtils.TraverseProperty = function (prop) {
            if (prop.propertyType != PropertyType.PROPERTY) {
                for (var i = prop.numProperties; i > 0; i--) {
                    ExpressionHandlerUtils.TraverseProperty(prop.property(i));
                }
            }
            else {
                ExpressionHandlerUtils.ConvertPropertyExpressionToKeyframes(prop);
            }
        };
        ExpressionHandlerUtils.RemoveExpressionsInComp = function (myComp, finished, deep) {
            for (var i = 0; i < finished.length; i++) {
                if (finished[i] == myComp.id) {
                    return;
                }
            }
            finished.push(myComp.id);
            myComp.openInViewer();
            var subComps = [];
            for (var i = 1; i <= myComp.numLayers; i++) {
                var myLayer = myComp.layer(i);
                myLayer.selected = false;
                myLayer.locked = false;
                for (var k = 1; k <= myLayer.numProperties; k += 1) {
                    ExpressionHandlerUtils.TraverseProperty(myLayer.property(k));
                }
                if (myLayer instanceof AVLayer) {
                    var source = myLayer.source;
                    if (source instanceof CompItem) {
                        subComps.push(source);
                    }
                }
            }
            if (deep) {
                for (var i = 0; i < subComps.length; i++) {
                    ExpressionHandlerUtils.RemoveExpressionsInComp(subComps[i], finished, deep);
                }
            }
        };
        ExpressionHandlerUtils.RemoveExpressionControls = function (myComp, finished, deep) {
            for (var i = 0; i < finished.length; i++) {
                if (finished[i] == myComp.id) {
                    return;
                }
            }
            finished.push(myComp.id);
            var subComps = [];
            for (var i = 1; i <= myComp.numLayers; i++) {
                var myLayer = myComp.layer(i);
                if (myLayer instanceof AVLayer) {
                    var source = myLayer.source;
                    if (source instanceof CompItem) {
                        subComps.push(source);
                    }
                }
                if (LayerTypeUtils.IsBaseAVLayer(myLayer)) {
                    ExpressionHandlerUtils.RemoveLayerExpressionControlEffects(myLayer);
                }
            }
            if (deep) {
                for (var i = 0; i < subComps.length; i++) {
                    ExpressionHandlerUtils.RemoveExpressionControls(subComps[i], finished, deep);
                }
            }
        };
        ExpressionHandlerUtils.clear = function (comp, deep) {
            ExpressionHandlerUtils.RemoveExpressionsInComp(comp, [], deep);
            ExpressionHandlerUtils.RemoveExpressionControls(comp, [], deep);
        };
        ExpressionHandlerUtils.kExpressionControlEffects = [
            "ADBE Point3D Control",
            "ADBE Angle Control",
            "ADBE Checkbox Control",
            "ADBE Color Control",
            "ADBE Point Control",
            "ADBE Slider Control",
            "ADBE Layer Control"
        ];
        return ExpressionHandlerUtils;
    }());
    var PixelAspectHandler = (function () {
        function PixelAspectHandler() {
        }
        PixelAspectHandler.HandleCompItem = function (compItem) {
            compItem.pixelAspect = 1;
        };
        PixelAspectHandler.HandleFootageItem = function (footage) {
            if (footage.usedIn.length > 0 && footage.pixelAspect != 1) {
                Settings.WriteLogContent("Begin Handle Pixel Aspect:" + footage.file.fsName);
                var width = Math.ceil(footage.width * footage.pixelAspect);
                var height = footage.height;
                var comp = app.project.items.addComp(footage.name + "_par_fixed", width, height, 1, footage.duration, footage.frameRate);
                comp.layers.add(footage);
                var newfile = Settings.NewCacheAsset(Settings.NewCacheAssetName(".mov"));
                RenderUtils.RenderComp(comp, footage.mainSource.hasAlpha ? RenderUtils.kStraightAlphaVideoRenderTemplate : RenderUtils.kNormalVideoRenderTemplate, newfile);
                DomUtils.ReplaceFootageItem(footage, new File(newfile));
                footage.pixelAspect = 1;
                comp.remove();
                Settings.WriteLogContent("End Handle Pixel Aspect");
            }
        };
        PixelAspectHandler.HandleProjectItems = function () {
            var num = app.project.numItems;
            for (var i = 1; i <= num; i++) {
                var item = app.project.item(i);
                if (item instanceof CompItem) {
                    PixelAspectHandler.HandleCompItem(item);
                }
                else if (item instanceof FootageItem) {
                    PixelAspectHandler.HandleFootageItem(item);
                }
            }
        };
        return PixelAspectHandler;
    }());
    var CompUnsupportedBlendModeHandler = (function () {
        function CompUnsupportedBlendModeHandler(comp) {
            this.mComp = comp;
            this.mUIIdx = [];
            this.mUnsupportedLayers = [];
            for (var i = 1; i <= this.mComp.numLayers; i++) {
                if (LayerTypeUtils.IsBaseAVLayer(this.mComp.layer(i))) {
                    if (!CompUnsupportedBlendModeHandler.IsLayerBlendModeSupported(this.mComp.layer(i))) {
                        this.mUnsupportedLayers.push(this.mComp.layer(i));
                    }
                }
            }
        }
        CompUnsupportedBlendModeHandler.IsLayerBlendModeSupported = function (layer) {
            var mode = layer.blendingMode;
            switch (mode) {
                case BlendingMode.NORMAL:
                case BlendingMode.LIGHTEN:
                case BlendingMode.DARKEN:
                case BlendingMode.MULTIPLY:
                case BlendingMode.ADD:
                case BlendingMode.DIFFERENCE:
                case BlendingMode.EXCLUSION:
                case BlendingMode.SCREEN:
                case BlendingMode.SOFT_LIGHT:
                case BlendingMode.HARD_LIGHT:
                case BlendingMode.COLOR_DODGE:
                case BlendingMode.COLOR_BURN:
                case BlendingMode.CLASSIC_COLOR_BURN:
                case BlendingMode.LINEAR_DODGE:
                case BlendingMode.LINEAR_BURN:
                case BlendingMode.LINEAR_LIGHT:
                case BlendingMode.VIVID_LIGHT:
                case BlendingMode.PIN_LIGHT:
                case BlendingMode.HARD_MIX:
                case BlendingMode.OVERLAY:
                case BlendingMode.HUE:
                case BlendingMode.SATURATION:
                case BlendingMode.COLOR:
                case BlendingMode.LUMINOSITY:
                    return true;
            }
            return false;
        };
        return CompUnsupportedBlendModeHandler;
    }());
    var UnsupportedBlendModeHandler = (function () {
        function UnsupportedBlendModeHandler(comp) {
            this.mMainComp = comp;
            this.mAllComps = [];
            this.digUnsupportedLayers(this.mMainComp, []);
        }
        UnsupportedBlendModeHandler.prototype.digUnsupportedLayers = function (comp, finished) {
            for (var i = 0; i < finished.length; i++) {
                if (finished[i] == comp.id) {
                    return;
                }
            }
            finished.push(comp.id);
            var handle = new CompUnsupportedBlendModeHandler(comp);
            if (handle.mUnsupportedLayers.length > 0) {
                this.mAllComps.push(handle);
            }
            for (var i = 1; i < comp.numLayers; i++) {
                var layer = comp.layer(i);
                if (layer instanceof AVLayer && layer.source instanceof CompItem) {
                    this.digUnsupportedLayers(layer.source, finished);
                }
            }
        };
        UnsupportedBlendModeHandler.prototype.selectAt = function (idx) {
            for (var i = 0; i < this.mAllComps.length; i++) {
                var comp = this.mAllComps[i];
                for (var g = 0; g < comp.mUIIdx.length; g++) {
                    if (comp.mUIIdx[g] == idx) {
                        comp.mUnsupportedLayers[g].selected = true;
                        return;
                    }
                }
            }
        };
        UnsupportedBlendModeHandler.prototype.getLayerAt = function (idx) {
            for (var i = 0; i < this.mAllComps.length; i++) {
                var comp = this.mAllComps[i];
                for (var g = 0; g < comp.mUIIdx.length; g++) {
                    if (comp.mUIIdx[g] == idx) {
                        return comp.mUnsupportedLayers[g];
                    }
                }
            }
            return null;
        };
        return UnsupportedBlendModeHandler;
    }());
    var UnusedLayerUtils = (function () {
        function UnusedLayerUtils() {
        }
        UnusedLayerUtils.IsLayerInCompDuration = function (layer) {
            var inPoint = layer.inPoint;
            var outPoint = layer.outPoint;
            var duration = layer.containingComp.duration;
            if ((inPoint <= 0 && outPoint <= 0) || (inPoint >= duration && outPoint >= duration)) {
                return false;
            }
            return true;
        };
        UnusedLayerUtils.ClearUnusedLayers = function (comp, recursive) {
            var count = 0;
            var relationship = new CompRelationship(comp);
            var layers = DomUtils.GetLayersInComp(comp);
            var deadLayers = [];
            var preComps = [];
            for (var index = 0; index < layers.length; index++) {
                var layer = layers[index];
                var removed = false;
                for (var index_1 = 0; index_1 < relationship.mAllLayerRelationships.length; index_1++) {
                    var element = relationship.mAllLayerRelationships[index_1];
                    if (element.mRelatedLayer == layer) {
                        if (!element.hasRelationship(LayerRelationshipType.kParentChild) && !UnusedLayerUtils.IsLayerInCompDuration(layer)) {
                            deadLayers.push(layer);
                            removed = true;
                        }
                    }
                }
                if (!removed && recursive && layer instanceof AVLayer && layer.source instanceof CompItem) {
                    preComps.push(layer.source);
                }
            }
            count += deadLayers.length;
            for (var index = 0; index < deadLayers.length; index++) {
                var layer = deadLayers[index];
                layer.remove();
            }
            for (var index = 0; index < preComps.length; index++) {
                var comp_1 = preComps[index];
                count += UnusedLayerUtils.ClearUnusedLayers(comp_1, true);
            }
            return count;
        };
        return UnusedLayerUtils;
    }());
    var LayerRelationshipType;
    (function (LayerRelationshipType) {
        LayerRelationshipType[LayerRelationshipType["kParentChild"] = 0] = "kParentChild";
        LayerRelationshipType[LayerRelationshipType["kTrackMatte"] = 1] = "kTrackMatte";
        LayerRelationshipType[LayerRelationshipType["kLayerInput"] = 2] = "kLayerInput";
        LayerRelationshipType[LayerRelationshipType["kAdjustment"] = 3] = "kAdjustment";
    })(LayerRelationshipType || (LayerRelationshipType = {}));
    var LayerRelationship = (function () {
        function LayerRelationship(type, prop) {
            if (prop === void 0) { prop = null; }
            this.mRelateType = type;
            this.mProperty = prop;
        }
        return LayerRelationship;
    }());
    var RelatedLayer = (function () {
        function RelatedLayer(host, related) {
            this.mRelationships = [];
            this.mHostLayer = host;
            this.mRelatedLayer = related;
        }
        RelatedLayer.prototype.hasRelationship = function (type) {
            for (var i = 0; i < this.mRelationships.length; i++) {
                if (this.mRelationships[i].mRelateType == type) {
                    return true;
                }
            }
            return false;
        };
        RelatedLayer.prototype.addParentChildRelationship = function () {
            this.mRelationships.push(new LayerRelationship(LayerRelationshipType.kParentChild));
        };
        RelatedLayer.prototype.addTrackMatteRelationship = function () {
            this.mRelationships.push(new LayerRelationship(LayerRelationshipType.kTrackMatte));
        };
        RelatedLayer.prototype.addLayerInputRelationship = function () {
            this.mRelationships.push(new LayerRelationship(LayerRelationshipType.kLayerInput));
        };
        RelatedLayer.prototype.addAdjustmentRelationship = function () {
            this.mRelationships.push(new LayerRelationship(LayerRelationshipType.kAdjustment));
        };
        return RelatedLayer;
    }());
    var CompRelationship = (function () {
        function CompRelationship(comp) {
            this.mComp = comp;
            this.mAllLayerRelationships = [];
            for (var j = 1; j <= comp.numLayers; j += 1) {
                var layer = comp.layer(j);
                if (layer.parent) {
                    var relationship = this.addLayerRelationship(layer, layer.parent);
                    relationship.addParentChildRelationship();
                }
                if (LayerTypeUtils.IsBaseAVLayer(layer)) {
                    if (layer.isTrackMatte) {
                        var matted = comp.layer(layer.index + 1);
                        if (matted.enabled) {
                            var relationship = this.addLayerRelationship(layer, matted);
                            relationship.addTrackMatteRelationship();
                        }
                    }
                    if (layer.adjustmentLayer && layer.enabled && DomUtils.IsLayerReallyHasEffects(layer)) {
                        for (var k = j; k <= comp.numLayers; k++) {
                            var ll = comp.layer(k);
                            if (LayerTypeUtils.IsBaseAVLayer(ll)) {
                                var relationship = this.addLayerRelationship(layer, ll);
                                relationship.addAdjustmentRelationship();
                            }
                        }
                    }
                }
                for (var k = 1; k <= layer.numProperties; k += 1) {
                    this.traverseProperty(layer.property(k), layer);
                }
            }
        }
        CompRelationship.prototype.traverseProperty = function (prop, layer) {
            if (prop.propertyType != PropertyType.PROPERTY) {
                for (var i = prop.numProperties; i > 0; i--) {
                    this.traverseProperty(prop.property(i), layer);
                }
            }
            else {
                var property = prop;
                if (property.propertyValueType == PropertyValueType.LAYER_INDEX && property.value !== 0) {
                    var refLayer = this.mComp.layer(property.value);
                    var relationship = this.addLayerRelationship(refLayer, layer);
                    relationship.addLayerInputRelationship();
                }
            }
        };
        CompRelationship.prototype.getLayerRelationship = function (host, relate) {
            for (var index = 0; index < this.mAllLayerRelationships.length; index++) {
                var element = this.mAllLayerRelationships[index];
                if (element.mHostLayer == host && element.mRelatedLayer == relate) {
                    return element;
                }
            }
            return null;
        };
        CompRelationship.prototype.getAllLayerRelationships = function (host) {
            var relationships = [];
            for (var index = 0; index < this.mAllLayerRelationships.length; index++) {
                var element = this.mAllLayerRelationships[index];
                if (element.mHostLayer == host) {
                    relationships.push(element);
                }
            }
            return relationships;
        };
        CompRelationship.prototype.getAllLayerRelatedTo = function (relate) {
            var relationships = [];
            for (var index = 0; index < this.mAllLayerRelationships.length; index++) {
                var element = this.mAllLayerRelationships[index];
                if (element.mRelatedLayer == relate || element.mHostLayer == relate) {
                    relationships.push(element);
                }
            }
            return relationships;
        };
        CompRelationship.prototype.getLayerRelated = function (layer, recursive, result) {
            for (var index = 0; index < this.mAllLayerRelationships.length; index++) {
                var element = this.mAllLayerRelationships[index];
                if (element.mRelatedLayer == layer) {
                    if (element.hasRelationship(LayerRelationshipType.kAdjustment) ||
                        element.hasRelationship(LayerRelationshipType.kParentChild) ||
                        element.hasRelationship(LayerRelationshipType.kTrackMatte)) {
                        result.push(element.mHostLayer);
                        if (recursive) {
                            this.getLayerRelated(layer, recursive, result);
                        }
                    }
                }
            }
        };
        CompRelationship.prototype.isHostAndRelateLayerHasRelationships = function (host, relate) {
            var relationship = this.getLayerRelationship(host, relate);
            if (relationship != null) {
                return relationship.mRelatedLayer != null && relationship.mRelationships.length > 0;
            }
            return false;
        };
        CompRelationship.prototype.addLayerRelationship = function (host, layer) {
            var relationship = this.getLayerRelationship(host, layer);
            if (relationship == null) {
                relationship = new RelatedLayer(host, layer);
                this.mAllLayerRelationships.push(relationship);
            }
            return relationship;
        };
        return CompRelationship;
    }());
    var ColorGradeUtils = (function () {
        function ColorGradeUtils() {
        }
        ColorGradeUtils.HasLookUpImageEffect = function () {
            var effects = app.effects;
            for (var effect in effects) {
                var element = effects[effect];
                if (element.matchName == ColorGradeUtils.kLookUpImageName) {
                    return true;
                }
            }
            return false;
        };
        ColorGradeUtils.IsSupportedColorGradeEffect = function (matchName) {
            if (ColorGradeUtils.kSupportedBatchColorGradeEffectString.length == 0) {
                ColorGradeUtils.kSupportedBatchColorGradeEffectString = ColorGradeUtils.kSupportedBatchColorGradeEffects.join();
            }
            return ColorGradeUtils.kSupportedBatchColorGradeEffectString.indexOf(matchName) != -1;
        };
        ColorGradeUtils.GetLayerColorGradeEffects = function (layer) {
            var effects = [];
            var numEffects = layer.effect.numProperties;
            for (var e = 1; e <= numEffects; e++) {
                var effect = layer.effect.property(e);
                if (effect.enabled && ColorGradeUtils.IsSupportedColorGradeEffect(effect.matchName)) {
                    effects.push(e);
                }
            }
            return effects.length != numEffects ? [] : effects;
        };
        ColorGradeUtils.TurnOffOtherEffects = function (layer, backupState, exclude) {
            backupState.splice(0, backupState.length);
            var numEffects = layer.effect.numProperties;
            var excludeIndex = 0;
            for (var e = 1; e <= numEffects; e++) {
                var effect = layer.effect.property(e);
                backupState.push(effect.enabled);
                if (effect.enabled) {
                    if (e == exclude[excludeIndex]) {
                        excludeIndex++;
                    }
                    else {
                        effect.enabled = false;
                    }
                }
            }
        };
        ColorGradeUtils.RestoreLayerEffectsState = function (layer, backupState) {
            var numEffects = layer.effect.numProperties;
            for (var e = 1; e <= numEffects; e++) {
                var effect = layer.effect.property(e);
                effect.enabled = backupState[e];
            }
        };
        ColorGradeUtils.RemoveLayerEffects = function (layer, effectIndices) {
            effectIndices.sort(function (a, b) {
                if (a < b) {
                    return -1;
                }
                if (a > b) {
                    return 1;
                }
                return 0;
            });
            var offset = 0;
            for (var idx = 0; idx < effectIndices.length; idx++) {
                layer.effect.property(effectIndices[idx] - offset).remove();
                offset++;
            }
        };
        ColorGradeUtils.ProcessLayerColorGradeEffects = function (layer) {
            function removeKeyframes(prop) {
                if (prop.propertyType == PropertyType.PROPERTY) {
                    var property = prop;
                    while (property.numKeys > 0) {
                        property.removeKey(1);
                    }
                }
                else {
                    for (var i = prop.numProperties; i > 0; i--) {
                        removeKeyframes(prop.property(i));
                    }
                }
            }
            function hasKeyframes(prop) {
                if (prop.propertyType == PropertyType.PROPERTY) {
                    var property = prop;
                    if (property.numKeys > 0) {
                        return true;
                    }
                }
                else {
                    for (var i = prop.numProperties; i > 0; i--) {
                        if (hasKeyframes(prop.property(i))) {
                            return true;
                        }
                    }
                }
                return false;
            }
            function effectsHasKeyframes(ll) {
                var numEffects = ll.effect.numProperties;
                for (var e = 1; e <= numEffects; e++) {
                    var effect = ll.effect.property(e);
                    if (effect.enabled) {
                        if (hasKeyframes(effect)) {
                            return true;
                        }
                    }
                }
                return false;
            }
            if (ColorGradeUtils.HasLookUpImageEffect()) {
                var colorEffects = ColorGradeUtils.GetLayerColorGradeEffects(layer);
                if (colorEffects.length > 0) {
                    Settings.WriteLogContent("Begin Proccess Comp:" + layer.containingComp.name + " layer:" + layer.index.toString() + " Name:" + layer.name + " Color Grade Effects");
                    var footageImpOpt = new ImportOptions(new File(Settings.BinFolder() + "/lookup.png"));
                    var footage = app.project.importFile(footageImpOpt);
                    var comp = app.project.items.addComp("ve_temp_lookup_comp", 512, 512, 1, layer.outPoint - layer.inPoint, layer.containingComp.frameRate);
                    layer.copyToComp(comp);
                    var tempLayer = comp.layer(1);
                    if (!(LayerTypeUtils.IsBaseAVLayer(tempLayer))) {
                        return;
                    }
                    var backupStates = [];
                    ColorGradeUtils.TurnOffOtherEffects(tempLayer, backupStates, colorEffects);
                    tempLayer.replaceSource(footage, true);
                    tempLayer.inPoint = 0;
                    tempLayer.adjustmentLayer = false;
                    tempLayer.threeDLayer = false;
                    removeKeyframes(tempLayer.position);
                    removeKeyframes(tempLayer.anchorPoint);
                    removeKeyframes(tempLayer.scale);
                    removeKeyframes(tempLayer.rotation);
                    removeKeyframes(tempLayer.opacity);
                    tempLayer.position.setValue([0, 0]);
                    tempLayer.anchorPoint.setValue([0, 0]);
                    tempLayer.scale.setValue([100, 100]);
                    tempLayer.rotation.setValue(0);
                    tempLayer.opacity.setValue(100);
                    while (tempLayer.mask.numProperties > 0) {
                        tempLayer.mask.property(1).remove();
                    }
                    tempLayer.trackMatteType = TrackMatteType.NO_TRACK_MATTE;
                    var newfile = "";
                    if (effectsHasKeyframes(tempLayer)) {
                        newfile = Settings.NewCacheAsset(Settings.NewCacheAssetName(".mov"));
                        RenderUtils.RenderComp(comp, RenderUtils.kNormalVideoRenderTemplate, newfile);
                    }
                    else {
                        newfile = Settings.NewCacheAsset(Settings.NewCacheAssetName(".png"));
                        RenderUtils.SaveCompToSingleImage(comp, newfile, Math.abs(tempLayer.inPoint));
                    }
                    comp.remove();
                    footage.remove();
                    var lookUpImpOpt = new ImportOptions(new File(newfile));
                    lookUpImpOpt.sequence = false;
                    var lookup = app.project.importFile(lookUpImpOpt);
                    var lookupLayer = layer.containingComp.layers.add(lookup);
                    lookupLayer.startTime = layer.startTime;
                    lookupLayer.inPoint = layer.inPoint;
                    lookupLayer.moveToBeginning();
                    lookupLayer.enabled = false;
                    ColorGradeUtils.RemoveLayerEffects(layer, colorEffects);
                    var effect = layer.effect.addProperty(ColorGradeUtils.kLookUpImageName);
                    var inputLayerProp = effect.property("VE_Look_Up_Image-0002");
                    inputLayerProp.setValue(1);
                    Settings.WriteLogContent("End Process Layer Color Grade Effects");
                }
            }
        };
        ColorGradeUtils.ProcessCompColorGradeEffects = function (comp, finished) {
            for (var i = 0; i < finished.length; i++) {
                if (finished[i] == comp.id) {
                    return;
                }
            }
            finished.push(comp.id);
            for (var i = 1; i <= comp.numLayers; i++) {
                var layer = comp.layer(i);
                if (LayerTypeUtils.IsBaseAVLayer(layer)) {
                    ColorGradeUtils.ProcessLayerColorGradeEffects(layer);
                }
                if (layer instanceof AVLayer && layer.source instanceof CompItem) {
                    ColorGradeUtils.ProcessCompColorGradeEffects(layer.source, finished);
                }
            }
        };
        ColorGradeUtils.kLookUpImageName = "VE_Look_Up_Image";
        ColorGradeUtils.kSupportedBatchColorGradeEffectString = "";
        ColorGradeUtils.kSupportedBatchColorGradeEffects = [
            "ADBE AutoColor",
            "ADBE AutoContrast",
            "ADBE AutoLevels",
            "ADBE Black&White",
            "ADBE Brightness & Contrast 2",
            "ADBE Broadcast Colors",
            "CS Color Neutralizer",
            "CC Color Offset",
            "CS Kernel",
            "CC Toner",
            "ADBE Change Color",
            "ADBE Change To Color",
            "ADBE CHANNEL MIXER",
            "ADBE Color Balance 2",
            "ADBE Color Balance (HLS)",
            "ADBE CurvesCustom",
            "ADBE CurvesCustom",
            "ADBE Equalize",
            "ADBE Exposure2",
            "ADBE Gamma/Pedestal/Gain2",
            "ADBE HUE SATURATION",
            "ADBE Leave Color",
            "ADBE Easy Levels2",
            "ADBE Pro Levels2",
            "ADBE PhotoFilterPS",
            "ADBE PS Arbitrary Map",
            "ADBE SelectiveColor",
            "ADBE ShadowHighlight",
            "ADBE Tint",
            "ADBE Tritone",
            "ADBE Vibrance",
            "ADBE Lumetri"
        ];
        return ColorGradeUtils;
    }());
    var Settings = (function () {
        function Settings() {
        }
        Settings.InitSetting = function (extensionRoot, appScriptRoot) {
            Settings.kExtensionRoot = extensionRoot;
            Settings.kAppScriptRoot = appScriptRoot;
            RenderUtils.RenderTemplatesCheck();
        };
        Settings.BinFolder = function () {
            return Settings.kExtensionRoot + "/.bin";
        };
        Settings.GetCacheFolder = function () {
            var dir = null;
            if (Settings.kCacheFolder == Settings.kDefaultCacheFolder && app.project.file) {
                dir = app.project.file.parent.fsName + "/veclean";
            }
            else {
                dir = Settings.kCacheFolder;
            }
            if (dir) {
                var f = new Folder(dir);
                if (!f.exists) {
                    f.create();
                }
            }
            return dir;
        };
        Settings.GetLogFile = function () {
            if (Settings.kLogFile == null) {
                Settings.kLogFile = new File(Settings.GetCacheFolder() + "/log.txt");
                if (!Settings.kLogFile.exists) {
                    Settings.kLogFile.open("w");
                }
                else {
                    Settings.kLogFile.open("a");
                }
            }
            return Settings.kLogFile;
        };
        Settings.WriteLogContent = function (content) {
            if (Settings.kEnableLog) {
                var date = new Date();
                content = "[" + date.toLocaleDateString() + "-" + date.toLocaleTimeString() + "]:" + content;
                Settings.GetLogFile().writeln(content);
                Settings.kLogFile.close();
                Settings.kLogFile.open("a");
            }
        };
        Settings.CloseLogFile = function () {
            if (Settings.kLogFile) {
                Settings.kLogFile.close();
                Settings.kLogFile = null;
            }
        };
        Settings.GetProjectFolder = function () {
            var dir = null;
            if (app.project.file) {
                dir = app.project.file.parent.fsName;
            }
            return dir;
        };
        Settings.GetCacheAssetsFolder = function () {
            var cacheFolder = Settings.GetCacheFolder();
            if (cacheFolder) {
                var date = new Date();
                var dir = cacheFolder + "/" + (date.getYear() + 1900) + "-" + (date.getMonth() + 1) + "-" + date.getDate();
                var f = new Folder(dir);
                if (!f.exists) {
                    f.create();
                }
                return dir;
            }
            return null;
        };
        Settings.NewCacheAssetName = function (extension) {
            var name = "cache" + Settings.kCacheAssetCounter.toString() + extension;
            var newCounter = Settings.kCacheAssetCounter - 1;
            var files = (new Folder(Settings.GetCacheAssetsFolder())).getFiles(null);
            for (var i = 0; i < files.length; i++) {
                var f = files[i];
                var s = f.name.indexOf("cache");
                if (s == 0) {
                    var end = f.name.lastIndexOf(".");
                    if (end < f.name.length) {
                        var counterStr = f.name.substr(5, end - 5);
                        var count = parseInt(counterStr);
                        if (!isNaN(count)) {
                            newCounter = Math.max(newCounter, count);
                        }
                    }
                }
            }
            Settings.kCacheAssetCounter = newCounter + 1;
            name = "cache" + Settings.kCacheAssetCounter.toString() + extension;
            Settings.kCacheAssetCounter++;
            return name;
        };
        Settings.NewCacheAsset = function (name, autoCorrect) {
            if (autoCorrect === void 0) { autoCorrect = true; }
            var folder = Settings.GetCacheAssetsFolder();
            if (folder) {
                var path = folder + "/" + name;
                if ((new File(path)).exists) {
                    if (autoCorrect) {
                        return Settings.NewCacheAsset("0" + name, autoCorrect);
                    }
                    else {
                        return null;
                    }
                }
                return path;
            }
            return null;
        };
        Settings.IsDefaultCacheFolder = function () {
            return Settings.kCacheFolder == Settings.kDefaultCacheFolder;
        };
        Settings.SetCacheFolder = function (path) {
            if (path && path != Settings.kCacheFolder) {
                Settings.kCacheFolder = path;
            }
        };
        Settings.IsWindows = function () {
            return $.os.toLocaleLowerCase().indexOf("mac") == -1;
        };
        Settings.IsMac = function () {
            return $.os.toLocaleLowerCase().indexOf("mac") != -1;
        };
        Settings.kEnableLog = false;
        Settings.kCacheAssetCounter = 0;
        Settings.kDefaultCacheFolder = "default";
        Settings.kCacheFolder = Settings.kDefaultCacheFolder;
        Settings.kLogFile = null;
        Settings.kExtensionRoot = "";
        Settings.kAppScriptRoot = "";
        return Settings;
    }());
    VECleaner.Settings = Settings;
    var CompCleaner = (function () {
        function CompCleaner(comp) {
            this.mComp = comp;
            this.mEditableImageLayers = [];
            this.mEditableTextLayers = [];
            this.mUntouchableLayers = [];
            this.updateLayerRelationships();
        }
        CompCleaner.ClearCompSelection = function (comp, finished) {
            for (var i = 0; i < finished.length; i++) {
                if (finished[i] == comp.id) {
                    return;
                }
            }
            finished.push(comp.id);
            var subComps = [];
            for (var i = 1; i <= comp.numLayers; i++) {
                var myLayer = comp.layer(i);
                myLayer.selected = false;
                if (myLayer instanceof AVLayer) {
                    var source = myLayer.source;
                    if (source instanceof CompItem) {
                        subComps.push(source);
                    }
                }
            }
            for (var i = 0; i < subComps.length; i++) {
                CompCleaner.ClearCompSelection(subComps[i], finished);
            }
        };
        CompCleaner.ClearSelection = function (comp) {
            Settings.WriteLogContent("Begin Clear Selection");
            CompCleaner.ClearCompSelection(comp, []);
            Settings.WriteLogContent("End Clear Selection");
        };
        CompCleaner.prototype.updateLayerRelationships = function () {
            this.mRelationships = new CompRelationship(this.mComp);
            this.collectEditableLayers(this.mComp);
            this.collectUntuchableLayers();
            this.mComp.openInViewer();
        };
        CompCleaner.prototype.collectEditableLayers = function (comp) {
            this.mEditableImageLayers = [];
            this.mEditableTextLayers = [];
            for (var i = 1; i <= comp.numLayers; i++) {
                var layer = comp.layer(i);
                if (LayerTypeUtils.IsBaseAVLayer(layer)) {
                    if (LayerMarkerUtils.IsEditableImageLayer(layer)) {
                        this.mEditableImageLayers.push(layer);
                    }
                    else if (layer instanceof TextLayer && LayerMarkerUtils.IsEditableTextLayer(layer)) {
                        this.mEditableTextLayers.push(layer);
                    }
                }
            }
        };
        CompCleaner.prototype.collectUntuchableLayers = function () {
            var self = this;
            self.mUntouchableLayers = [];
            function pushLayer(layer) {
                var index = 0;
                for (var i = 0; i < self.mUntouchableLayers.length; i++) {
                    if (self.mUntouchableLayers[i].index == layer.index) {
                        index = -1;
                        break;
                    }
                    else {
                        if (i == 0) {
                            if (self.mUntouchableLayers[i].index > layer.index) {
                                index = 0;
                                break;
                            }
                        }
                        else if (i == self.mUntouchableLayers.length - 1) {
                            if (self.mUntouchableLayers[i].index < layer.index) {
                                index = self.mUntouchableLayers.length;
                                break;
                            }
                        }
                        else {
                            if (self.mUntouchableLayers[i].index < layer.index && self.mUntouchableLayers[i + 1].index > layer.index) {
                                index = i + 1;
                                break;
                            }
                            else {
                                index = -1;
                            }
                        }
                    }
                }
                if (index != -1) {
                    self.mUntouchableLayers.splice(index, 0, layer);
                }
            }
            for (var i = 1; i <= this.mComp.numLayers; i++) {
                var layer = this.mComp.layer(i);
                if (LayerTypeUtils.IsBaseAVLayer(layer) && LayerMarkerUtils.DoesLayerIsOrContainsEditableLayer(layer)) {
                    var relatedLayers = this.mRelationships.getAllLayerRelatedTo(layer);
                    pushLayer(layer);
                    for (var r = 0; r < relatedLayers.length; r++) {
                        pushLayer(relatedLayers[r].mHostLayer);
                        pushLayer(relatedLayers[r].mRelatedLayer);
                    }
                }
            }
        };
        CompCleaner.removeUnusedEfffects = function (comp) {
            for (var i = 1; i <= comp.numLayers; i++) {
                var myLayer = comp.layer(i);
                if (LayerTypeUtils.IsBaseAVLayer(myLayer)) {
                    var layer = myLayer;
                    for (var e = 1; e <= layer.effect.numProperties; e++) {
                        if (!layer.effect.property(e).enabled) {
                            layer.effect.property(e).remove();
                            e--;
                        }
                    }
                }
                if (myLayer instanceof AVLayer) {
                    var source = myLayer.source;
                    if (source instanceof CompItem) {
                        this.removeUnusedEfffects(source);
                    }
                }
            }
        };
        CompCleaner.prototype.renderAndReplaceLayerInComp = function (layers) {
            function collectRelatedLayers(layer, relatedLayers) {
                var output = [layer];
                for (var i = 0; i < relatedLayers.length; i++) {
                    var related = relatedLayers[i];
                    if (related.mHostLayer != layer && related.mRelatedLayer != layer) {
                        if (related.mHostLayer.containingComp == layer.containingComp && ArrayUtils.DoesArrayContain(output, related.mHostLayer)) {
                            output.push(related.mHostLayer);
                        }
                        if (related.mRelatedLayer.containingComp == layer.containingComp && ArrayUtils.DoesArrayContain(output, related.mRelatedLayer)) {
                            output.push(related.mRelatedLayer);
                        }
                    }
                }
                return output;
            }
            var output = [];
            var firstAVLayer = null;
            for (var i = 0; i < layers.length; i++) {
                if (LayerTypeUtils.IsBaseAVLayer(layers[i])) {
                    if (firstAVLayer == null) {
                        firstAVLayer = layers[i];
                    }
                    output = output.concat(collectRelatedLayers(layers[i], this.mRelationships.getAllLayerRelatedTo(layers[i])));
                }
                else {
                    output.push(layers[i]);
                }
            }
            var ret = RenderUtils.RenderSelectedLayerAndReplace(this.mComp, output, firstAVLayer);
            this.updateLayerRelationships();
            return ret;
        };
        CompCleaner.prototype.renderLayerEffects = function () {
            function collectRelatedLayers(layer, relatedLayers) {
                var output = [layer];
                for (var i = 0; i < relatedLayers.length; i++) {
                    var related = relatedLayers[i];
                    if (related.mHostLayer != layer && related.mRelatedLayer != layer) {
                        if (related.mHostLayer.containingComp == layer.containingComp && ArrayUtils.DoesArrayContain(output, related.mHostLayer)) {
                            output.push(related.mHostLayer);
                        }
                        if (related.mRelatedLayer.containingComp == layer.containingComp && ArrayUtils.DoesArrayContain(output, related.mRelatedLayer)) {
                            output.push(related.mRelatedLayer);
                        }
                    }
                }
                return output;
            }
            for (var l = 1; l <= this.mComp.numLayers; l++) {
                var layer = this.mComp.layer(l);
                if (LayerTypeUtils.IsBaseAVLayer(layer)) {
                    var avlayer = layer;
                    if (((!LayerMarkerUtils.DoesLayerIsOrContainsEditableLayer(avlayer) && DomUtils.IsLayerReallyHasEffects(avlayer) && !avlayer.adjustmentLayer) || layer instanceof ShapeLayer) && !avlayer.threeDLayer) {
                        Settings.WriteLogContent("Begin Process Layer:" + l.toString() + " Name:" + layer.name);
                        this.renderAndReplaceLayerInComp([layer]);
                        Settings.WriteLogContent("End Process Layer");
                    }
                }
            }
        };
        CompCleaner.prototype.combineLayersAndRender = function () {
            var self = this;
            function isLayerRelated(layer, testLayers) {
                function isUntoucheable(test, testUntouchableLayers) {
                    for (var i = 0; i < testUntouchableLayers.length; i++) {
                        if (testUntouchableLayers[i] == test) {
                            return true;
                        }
                    }
                    return LayerMarkerUtils.DoesLayerIsOrContainsEditableLayer(layer);
                }
                if (LayerTypeUtils.IsBaseAVLayer(layer)) {
                    var hasEffects = layer.effect.numProperties > 0;
                    return hasEffects || isUntoucheable(layer, testLayers) || layer.threeDLayer;
                }
                return true;
            }
            function relatedBlendMode(layer) {
                if (layer.blendingMode != BlendingMode.NORMAL) {
                    for (var index = layer.index + 1; index <= layer.containingComp.numLayers; index++) {
                        var sl = layer.containingComp.layer(index);
                        if (LayerTypeUtils.IsBaseAVLayer(sl) && LayerMarkerUtils.DoesLayerIsOrContainsEditableLayer(sl)) {
                            return true;
                        }
                    }
                }
                return false;
            }
            function lastBlendMode(ls) {
                for (var i = ls.length - 1; i >= 0; i--) {
                    if (LayerTypeUtils.IsBaseAVLayer(ls[i])) {
                        return ls[i].blendingMode;
                    }
                }
                return null;
            }
            function removeLastAVLayer(ls) {
                for (var i = ls.length - 1; i >= 0; i--) {
                    if (LayerTypeUtils.IsBaseAVLayer(ls[i])) {
                        ls.splice(i, 1);
                    }
                }
            }
            function avlayerCount(ls) {
                var count = 0;
                for (var i = ls.length - 1; i >= 0; i--) {
                    if (LayerTypeUtils.IsBaseAVLayer(ls[i])) {
                        count++;
                    }
                }
                return count;
            }
            var layers = [];
            for (var i = 1; i <= this.mComp.numLayers; i++) {
                var layer = this.mComp.layer(i);
                var safe = false;
                var layerRelated = isLayerRelated(layer, self.mUntouchableLayers);
                if (!layerRelated) {
                    if (LayerTypeUtils.IsBaseAVLayer(layer)) {
                        var mode = LayerTypeUtils.IsBaseAVLayer(layer) ? layer.blendingMode : null;
                        var lastMode = lastBlendMode(layers);
                        var isBlendSafe = !relatedBlendMode(layer);
                        if (isBlendSafe && (mode == null || mode == lastMode)) {
                            safe = true;
                        }
                        else {
                            if (lastMode == null || lastMode == mode) {
                                safe = true;
                            }
                            else if (avlayerCount(layers) == 1) {
                                removeLastAVLayer(layers);
                                safe = true;
                            }
                        }
                    }
                }
                if (safe) {
                    layers.push(layer);
                }
                else {
                    if (layers.length == 1) {
                        layers = [];
                    }
                    else if (layers.length > 1) {
                        break;
                    }
                }
            }
            if (layers.length > 1) {
                Settings.WriteLogContent("Begin Process Layer:" + layers[0].index + " to " + layers[layers.length - 1].index);
                var dstBlend = lastBlendMode(layers);
                var precomplayer = this.renderAndReplaceLayerInComp(layers);
                if (precomplayer) {
                    precomplayer.blendingMode = dstBlend == null ? BlendingMode.NORMAL : dstBlend;
                }
                Settings.WriteLogContent("End Process Layer");
                return this.combineLayersAndRender();
            }
            return true;
        };
        return CompCleaner;
    }());
    var ThreeDLayerGroup = (function () {
        function ThreeDLayerGroup(comp, startIndex) {
            this.mComp = comp;
            this.mStartIndex = startIndex;
            this.mCount = 1;
            this.mUIIdx = -1;
            for (var i = startIndex + 1; i <= this.mComp.numLayers; i++) {
                var layer = this.mComp.layer(i);
                if (LayerTypeUtils.IsBaseAVLayer(layer) && layer.threeDLayer && !LayerMarkerUtils.DoesLayerIsOrContainsEditableLayer(layer)) {
                    this.mCount++;
                }
                else {
                    break;
                }
            }
        }
        ThreeDLayerGroup.prototype.select = function () {
            CompCleaner.ClearSelection(this.mComp);
            this.mComp.openInViewer();
            for (var i = this.mStartIndex; i < this.mStartIndex + this.mCount; i++) {
                this.mComp.layer(i).selected = true;
            }
        };
        return ThreeDLayerGroup;
    }());
    var CompThreeDLayerGroups = (function () {
        function CompThreeDLayerGroups(comp) {
            this.mComp = comp;
            this.mGroups = [];
            for (var i = 1; i <= this.mComp.numLayers; i++) {
                var layer = this.mComp.layer(i);
                if (LayerTypeUtils.IsBaseAVLayer(layer) && layer.threeDLayer && !LayerMarkerUtils.DoesLayerIsOrContainsEditableLayer(layer)) {
                    var group = new ThreeDLayerGroup(this.mComp, i);
                    this.mGroups.push(group);
                    i = group.mStartIndex + group.mCount - 1;
                }
            }
        }
        CompThreeDLayerGroups.prototype.empty = function () {
            if (this.mGroups.length > 0) {
                return false;
            }
            return true;
        };
        return CompThreeDLayerGroups;
    }());
    var ThreeDLayerHandler = (function () {
        function ThreeDLayerHandler(comp) {
            this.mMainComp = comp;
            this.mAllComps = [];
            this.digThreeDLayer(comp, []);
        }
        ThreeDLayerHandler.prototype.digThreeDLayer = function (comp, finished) {
            for (var i = 0; i < finished.length; i++) {
                if (finished[i] == comp.id) {
                    return;
                }
            }
            finished.push(comp.id);
            this.mAllComps.push(new CompThreeDLayerGroups(comp));
            for (var i = 1; i <= comp.numLayers; i++) {
                var layer = comp.layer(i);
                if (layer instanceof AVLayer && layer.source instanceof CompItem) {
                    this.digThreeDLayer(layer.source, finished);
                }
            }
        };
        ThreeDLayerHandler.prototype.empty = function () {
            for (var i = 0; i < this.mAllComps.length; i++) {
                var comp = this.mAllComps[i];
                if (!comp.empty()) {
                    return false;
                }
            }
            return true;
        };
        ThreeDLayerHandler.prototype.selectAt = function (index) {
            for (var i = 0; i < this.mAllComps.length; i++) {
                var comp = this.mAllComps[i];
                if (!comp.empty()) {
                    for (var g = 0; g < comp.mGroups.length; g++) {
                        if (comp.mGroups[g].mUIIdx == index) {
                            comp.mGroups[g].select();
                            return;
                        }
                    }
                }
            }
        };
        return ThreeDLayerHandler;
    }());
    var ToolGroupInfo = (function () {
        function ToolGroupInfo(name, description) {
            if (description === void 0) { description = ""; }
            this.mIndex = -1;
            this.mDiskID = -1;
            this.mTools = [];
            this.mName = name;
            this.mDescription = description;
            this.mNeedSaveProject = false;
        }
        ToolGroupInfo.prototype.addTool = function (name, description, triggerFunc, diskID, needSavePorj) {
            if (needSavePorj === void 0) { needSavePorj = true; }
            var tool = {
                mName: name,
                mIndex: -1,
                mDiskID: diskID,
                mDescription: description,
                mNeedSaveProject: needSavePorj,
                trigger: triggerFunc,
                isTwoStep: function () { return false; },
                stepOne: function () { return ""; },
                stepTwo: function (cmd) { }
            };
            this.mTools.push(tool);
        };
        ToolGroupInfo.prototype.addTwoStepTool = function (name, description, stepOne, stepTwo, diskID, needSavePorj) {
            if (needSavePorj === void 0) { needSavePorj = true; }
            var tool = {
                mName: name,
                mIndex: -1,
                mDiskID: diskID,
                mDescription: description,
                mNeedSaveProject: needSavePorj,
                trigger: function () { return false; },
                isTwoStep: function () { return true; },
                stepOne: stepOne,
                stepTwo: stepTwo
            };
            this.mTools.push(tool);
        };
        ToolGroupInfo.prototype.getTool = function (index) {
            for (var i = 0; i < this.mTools.length; i++) {
                var tool = this.mTools[i];
                if (tool.mIndex == index) {
                    return tool;
                }
            }
            return null;
        };
        ToolGroupInfo.prototype.triggerTool = function (index) {
            for (var index_2 = 0; index_2 < this.mTools.length; index_2++) {
                var tool = this.mTools[index_2];
                if (tool.mIndex == index_2) {
                    return tool.trigger();
                }
            }
            return false;
        };
        ToolGroupInfo.prototype.trigger = function () {
            return true;
        };
        ToolGroupInfo.prototype.isTwoStep = function () {
            return false;
        };
        ToolGroupInfo.prototype.stepOne = function () {
            return "";
        };
        ToolGroupInfo.prototype.stepTwo = function (cmd) {
        };
        return ToolGroupInfo;
    }());
    var BasicTools = (function () {
        function BasicTools() {
        }
        BasicTools.BackupProject = function () {
            var proj = app.project;
            if (proj) {
                if (proj.file) {
                    proj.save();
                    var name = "ve_clean_" + proj.file.displayName;
                    proj.save(new File(Settings.GetProjectFolder() + "/" + name));
                }
                else {
                    alert(VECleaner.kTranslator.mData.HOST_BasicTools_BackupProject_msg1);
                }
            }
            return true;
        };
        BasicTools.Set8BitColorProject = function () {
            app.project.bitsPerChannel = 8;
            alert(VECleaner.kTranslator.mData.HOST_BasicTools_Set8BitColorProject_msg1);
            return true;
        };
        BasicTools.AddDefaultCamera = function () {
            function addDefaultCameraInComp(comp, finished) {
                if (!ArrayUtils.DoesArrayContain(finished, comp.id)) {
                    finished.push(comp.id);
                    var cameraLayers = DomUtils.GetCamerasLayerInComp(comp);
                    if (cameraLayers.length == 0) {
                        DomUtils.AddDefaultCameraToComp(comp);
                    }
                    for (var i = 1; i <= comp.numLayers; i++) {
                        var myLayer = comp.layer(i);
                        if (myLayer instanceof AVLayer) {
                            var source = myLayer.source;
                            if (source instanceof CompItem) {
                                addDefaultCameraInComp(source, finished);
                            }
                        }
                    }
                }
            }
            var comp = DomUtils.GetCurrentComp();
            if (comp != null) {
                var shouldDoIt = confirm(VECleaner.kTranslator.format(VECleaner.kTranslator.mData.HOST_BasicTools_AddDefaultCamera_msg1, comp.name), false, VECleaner.kTranslator.mData.HOST_BasicTools_AddDefaultCamera_msg2);
                if (shouldDoIt) {
                    addDefaultCameraInComp(comp, []);
                    alert(VECleaner.kTranslator.mData.HOST_BasicTools_AddDefaultCamera_msg3);
                }
            }
            else {
                alert(VECleaner.kTranslator.mData.HOST_BasicTools_AddDefaultCamera_msg4);
                return false;
            }
            return true;
        };
        BasicTools.RemoveUnsedLayers = function () {
            var comp = DomUtils.GetCurrentComp();
            if (comp != null) {
                var shouldDoIt = confirm(VECleaner.kTranslator.format(VECleaner.kTranslator.mData.HOST_BasicTools_RemoveUnsedLayers_msg1, comp.name), false, VECleaner.kTranslator.mData.HOST_BasicTools_RemoveUnsedLayers_msg2);
                if (shouldDoIt) {
                    var count = UnusedLayerUtils.ClearUnusedLayers(comp, true);
                    alert(VECleaner.kTranslator.format(VECleaner.kTranslator.mData.HOST_BasicTools_RemoveUnsedLayers_msg3, count.toString()));
                }
            }
            else {
                alert(VECleaner.kTranslator.mData.HOST_BasicTools_RemoveUnsedLayers_msg4);
                return false;
            }
            return true;
        };
        BasicTools.RemoveExpressionsDeep = function () {
            var comp = DomUtils.GetCurrentComp();
            if (comp != null) {
                var shouldDoIt = confirm(VECleaner.kTranslator.format(VECleaner.kTranslator.mData.HOST_BasicTools_RemoveExpressionsDeep_msg1, comp.name), false, VECleaner.kTranslator.mData.HOST_BasicTools_RemoveExpressionsDeep_msg2);
                if (shouldDoIt) {
                    ExpressionHandlerUtils.clear(comp, true);
                    alert(VECleaner.kTranslator.mData.HOST_BasicTools_RemoveExpressionsDeep_msg3);
                }
            }
            else {
                alert(VECleaner.kTranslator.mData.HOST_BasicTools_RemoveExpressionsDeep_msg4);
                return false;
            }
            return true;
        };
        return BasicTools;
    }());
    var MarkerTools = (function () {
        function MarkerTools() {
        }
        MarkerTools.AddEditImageMarker = function () {
            var layers = DomUtils.GetSelectedLayers();
            if (layers && layers.length > 0) {
                for (var index = 0; index < layers.length; index++) {
                    var layer = layers[index];
                    if (LayerTypeUtils.IsBaseAVLayer(layer)) {
                        LayerMarkerUtils.AddEditableImageMarker(layer);
                    }
                }
                return true;
            }
            return false;
        };
        MarkerTools.AddEditTextMarker = function () {
            var layers = DomUtils.GetSelectedLayers();
            if (layers && layers.length > 0) {
                for (var index = 0; index < layers.length; index++) {
                    var layer = layers[index];
                    if (layer instanceof TextLayer) {
                        LayerMarkerUtils.AddEditableTextMarker(layer);
                    }
                }
                return true;
            }
            return false;
        };
        MarkerTools.ClearLayerMarkers = function () {
            var layers = DomUtils.GetSelectedLayers();
            if (layers && layers.length > 0) {
                for (var index = 0; index < layers.length; index++) {
                    var layer = layers[index];
                    LayerMarkerUtils.ClearLayerMarkers(layer);
                }
                return true;
            }
            return false;
        };
        MarkerTools.ShowAllEditableLayers = function () {
            if (MarkerTools.kEditableLayerListPanel) {
                MarkerTools.kEditableLayerListPanel.close();
                MarkerTools.kEditableLayerListPanel = null;
            }
            if (MarkerTools.kEditableLayerListPanel == null) {
                MarkerTools.kEditableLayerListPanel = new EditableLayerPanel();
            }
            MarkerTools.kEditableLayerListPanel.updateContent();
            MarkerTools.kEditableLayerListPanel.show();
            return true;
        };
        MarkerTools.kEditableLayerListPanel = null;
        return MarkerTools;
    }());
    var PreRenderTools = (function () {
        function PreRenderTools() {
        }
        PreRenderTools.PrecompLayers = function () {
            var layers = DomUtils.GetSelectedLayers();
            if (layers && layers.length > 0) {
                PreCompUtils.PrecomposeAndAdjustDuraion(layers, layers[0].containingComp);
                return true;
            }
            else {
                alert(VECleaner.kTranslator.mData.HOST_PreRenderTools_PrecompLayers_msg1);
            }
            return false;
        };
        PreRenderTools.RenderLayersInPlace = function () {
            var layers = DomUtils.GetSelectedLayers();
            if (layers && layers.length > 0) {
                layers.sort(function (a, b) {
                    if (a.index < b.index) {
                        return -1;
                    }
                    if (a.index > b.index) {
                        return 1;
                    }
                    return 0;
                });
                var firstAVLayer = null;
                var hasEditableLayers = false;
                for (var i = 0; i < layers.length; i++) {
                    if (LayerTypeUtils.IsBaseAVLayer(layers[i])) {
                        if (firstAVLayer == null) {
                            firstAVLayer = layers[i];
                        }
                        if (LayerMarkerUtils.DoesLayerIsOrContainsEditableLayer(layers[i])) {
                            hasEditableLayers = true;
                            break;
                        }
                    }
                }
                if (firstAVLayer == null) {
                    alert(VECleaner.kTranslator.mData.HOST_PreRenderTools_RenderLayersInPlace_msg1);
                    return false;
                }
                if (hasEditableLayers == null) {
                    alert(VECleaner.kTranslator.mData.HOST_PreRenderTools_RenderLayersInPlace_msg2);
                    return false;
                }
                var comp = firstAVLayer.containingComp;
                var cameraLayers = DomUtils.GetCamerasLayerInComp(comp);
                var lights = DomUtils.GetLightLayerInComp(comp);
                RenderUtils.RenderSelectedLayerAndReplace(comp, layers.concat(cameraLayers).concat(lights), firstAVLayer);
                comp.openInViewer();
                return true;
            }
            else {
                alert(VECleaner.kTranslator.mData.HOST_PreRenderTools_RenderLayersInPlace_msg3);
            }
            return false;
        };
        PreRenderTools.Render3DLayers = function () {
            var layers = DomUtils.GetSelectedLayers();
            if (layers && layers.length > 0) {
                layers.sort(function (a, b) {
                    if (a.index < b.index) {
                        return -1;
                    }
                    if (a.index > b.index) {
                        return 1;
                    }
                    return 0;
                });
                var isSequence = true;
                var is3D = true;
                var firstAVLayer = null;
                var hasEditableLayers = false;
                for (var i = 0, pre = 0; i < layers.length; i++) {
                    if (LayerTypeUtils.IsBaseAVLayer(layers[i])) {
                        if (firstAVLayer == null) {
                            firstAVLayer = layers[i];
                        }
                        if (is3D && !layers[i].threeDLayer) {
                            is3D = false;
                            break;
                        }
                        if (LayerMarkerUtils.DoesLayerIsOrContainsEditableLayer(layers[i])) {
                            hasEditableLayers = true;
                            break;
                        }
                    }
                    if (i == 0) {
                        pre = layers[i].index;
                    }
                    else {
                        if (layers[i].index - pre != 1) {
                            isSequence = false;
                            break;
                        }
                        else {
                            pre = layers[i].index;
                        }
                    }
                }
                if (!isSequence) {
                    alert(VECleaner.kTranslator.mData.HOST_PreRenderTools_Render3DLayers_msg1);
                    return false;
                }
                if (!is3D) {
                    alert(VECleaner.kTranslator.mData.HOST_PreRenderTools_Render3DLayers_msg2);
                    return false;
                }
                if (firstAVLayer == null) {
                    alert(VECleaner.kTranslator.mData.HOST_PreRenderTools_Render3DLayers_msg3);
                    return false;
                }
                if (hasEditableLayers == null) {
                    alert(VECleaner.kTranslator.mData.HOST_PreRenderTools_Render3DLayers_msg4);
                    return false;
                }
                var comp = firstAVLayer.containingComp;
                var cameraLayers = DomUtils.GetCamerasLayerInComp(comp);
                var lights = DomUtils.GetLightLayerInComp(comp);
                RenderUtils.RenderSelectedLayerAndReplace(comp, layers.concat(cameraLayers).concat(lights), firstAVLayer);
                comp.openInViewer();
            }
            return true;
        };
        PreRenderTools.RenderCompLayerEffects = function () {
            var comp = DomUtils.GetCurrentComp();
            if (comp != null) {
                var shouldDoIt = confirm(VECleaner.kTranslator.format(VECleaner.kTranslator.mData.HOST_PreRenderTools_RenderCompLayerEffects_msg1, comp.name), false, VECleaner.kTranslator.mData.HOST_PreRenderTools_RenderCompLayerEffects_msg2);
                if (shouldDoIt) {
                    var cleaner = new CompCleaner(comp);
                    cleaner.renderLayerEffects();
                    comp.openInViewer();
                    alert(VECleaner.kTranslator.mData.HOST_PreRenderTools_RenderCompLayerEffects_msg3);
                }
            }
            else {
                alert(VECleaner.kTranslator.mData.HOST_PreRenderTools_RenderCompLayerEffects_msg4);
                return false;
            }
            return true;
        };
        PreRenderTools.CombineAndRenderCompLayers = function () {
            var comp = DomUtils.GetCurrentComp();
            if (comp != null) {
                var shouldDoIt = confirm(VECleaner.kTranslator.format(VECleaner.kTranslator.mData.HOST_PreRenderTools_CombineAndRenderCompLayers_msg1, comp.name), false, VECleaner.kTranslator.mData.HOST_PreRenderTools_CombineAndRenderCompLayers_msg2);
                if (shouldDoIt) {
                    var cleaner = new CompCleaner(comp);
                    cleaner.combineLayersAndRender();
                    comp.openInViewer();
                    alert(VECleaner.kTranslator.mData.HOST_PreRenderTools_CombineAndRenderCompLayers_msg3);
                }
            }
            else {
                alert(VECleaner.kTranslator.mData.HOST_PreRenderTools_CombineAndRenderCompLayers_msg4);
                return false;
            }
            return true;
        };
        PreRenderTools.RenderAsImage = function () {
            var layer = DomUtils.GetFirstSelectedLayer();
            if (layer && LayerTypeUtils.IsBaseAVLayer(layer)) {
                var comp = layer.containingComp;
                var index = layer.index;
                var layerTypes = LayerTypeUtils.GetlayerType(layer);
                if (!(layerTypes & LayerTypes.kPreCompLayer)) {
                    PreCompUtils.PrecomposeAndAdjustDuraion([layer], comp);
                    layer = comp.layer(index);
                }
                RenderUtils.RenderAndReplaceLayerComp(layer, false);
                return true;
            }
            return false;
        };
        PreRenderTools.CombineCompAudio = function () {
            var comp = DomUtils.GetCurrentComp();
            if (comp) {
                var shouldDoIt = confirm(VECleaner.kTranslator.format(VECleaner.kTranslator.mData.HOST_PreRenderTools_RenderAsAudio_msg5, comp.name));
                if (shouldDoIt) {
                    var path = Settings.NewCacheAsset(Settings.NewCacheAssetName(".mp3"));
                    var renderRet = RenderUtils.RenderComp(comp, RenderUtils.kAudioOnlyTemplate, path);
                    comp.openInViewer();
                    if (renderRet) {
                        DomUtils.DisableCompAudio(comp);
                        var impOpt = new ImportOptions(new File(path));
                        if (impOpt) {
                            var footage = app.project.importFile(impOpt);
                            comp.layers.add(footage).moveToEnd();
                            comp.openInViewer();
                            alert(VECleaner.kTranslator.mData.HOST_PreRenderTools_RenderAsAudio_msg2);
                            return true;
                        }
                    }
                    else {
                        alert(VECleaner.kTranslator.mData.HOST_PreRenderTools_RenderAsAudio_msg1);
                    }
                }
            }
            else {
                alert(VECleaner.kTranslator.mData.HOST_PreRenderTools_RenderAsAudio_msg3);
            }
            return false;
        };
        PreRenderTools.RenderPreComp = function () {
            var layers = DomUtils.GetSelectedLayers();
            if (layers && layers.length > 0) {
                var editableCount = 0;
                for (var l = 0; l < layers.length; l++) {
                    var layer = layers[l];
                    if (LayerTypeUtils.IsBaseAVLayer(layer) && LayerMarkerUtils.DoesLayerIsOrContainsEditableLayer(layer)) {
                        editableCount++;
                    }
                }
                var ret = confirm(VECleaner.kTranslator.format(VECleaner.kTranslator.mData.HOST_PreRenderTools_RenderPreComp_msg1, layers.length.toString()) + (editableCount > 0 ? VECleaner.kTranslator.format(VECleaner.kTranslator.mData.HOST_PreRenderTools_RenderPreComp_msg2, editableCount.toString()) : ""), false, VECleaner.kTranslator.mData.HOST_PreRenderTools_RenderPreComp_msg3);
                if (ret && layers.length > 0) {
                    var comp = layers[0].containingComp;
                    for (var l = 0; l < layers.length; l++) {
                        var layer = layers[l];
                        var layerTypes = LayerTypeUtils.GetlayerType(layer);
                        if (layerTypes & LayerTypes.kPreCompLayer && !LayerMarkerUtils.DoesLayerIsOrContainsEditableLayer(layer)) {
                            Settings.WriteLogContent("Begin Process Layer:" + l.toString() + " Name:" + layer.name);
                            RenderUtils.RenderAndReplaceLayerComp(layer);
                            Settings.WriteLogContent("End Process Layer");
                        }
                    }
                    comp.openInViewer();
                }
            }
            else {
                alert(VECleaner.kTranslator.mData.HOST_PreRenderTools_RenderPreComp_msg4);
                return false;
            }
            return true;
        };
        PreRenderTools.ProcessColorGradeEffects = function () {
            var comp = DomUtils.GetCurrentComp();
            if (comp != null) {
                var shouldDoIt = confirm(VECleaner.kTranslator.format(VECleaner.kTranslator.mData.HOST_PreRenderTools_ProcessColorGradeEffects_msg1, comp.name), false, VECleaner.kTranslator.mData.HOST_PreRenderTools_ProcessColorGradeEffects_msg2);
                if (shouldDoIt) {
                    ColorGradeUtils.ProcessCompColorGradeEffects(comp, []);
                    comp.openInViewer();
                    alert(VECleaner.kTranslator.mData.HOST_PreRenderTools_ProcessColorGradeEffects_msg3);
                }
            }
            else {
                alert(VECleaner.kTranslator.mData.HOST_PreRenderTools_ProcessColorGradeEffects_msg4);
                return false;
            }
            return true;
        };
        PreRenderTools.ProcessSelectedLayerMasks = function () {
            var layer = DomUtils.GetFirstSelectedLayer();
            if (layer instanceof AVLayer) {
                if (RenderUtils.ProcessLayerMasks(layer)) {
                    alert(VECleaner.kTranslator.mData.HOST_PreRenderTools_ProcessLayerMasks_msg1);
                }
                else {
                    alert(VECleaner.kTranslator.mData.HOST_PreRenderTools_ProcessLayerMasks_msg2);
                }
            }
            return true;
        };
        PreRenderTools.ProcessCompMasks = function () {
            var comp = DomUtils.GetCurrentComp();
            if (comp != null) {
                var shouldDoIt = confirm(VECleaner.kTranslator.format(VECleaner.kTranslator.mData.HOST_PreRenderTools_ProcessCompMasks_msg1, comp.name), false, VECleaner.kTranslator.mData.HOST_PreRenderTools_ProcessCompMasks_msg2);
                if (shouldDoIt) {
                    RenderUtils.ProcessCompMasks(comp, comp);
                    comp.openInViewer();
                    alert(VECleaner.kTranslator.mData.HOST_PreRenderTools_ProcessCompMasks_msg3);
                }
            }
            else {
                alert(VECleaner.kTranslator.mData.HOST_PreRenderTools_ProcessCompMasks_msg4);
                return false;
            }
            return true;
        };
        return PreRenderTools;
    }());
    var CompressVideoSourceSettingPanel = (function () {
        function CompressVideoSourceSettingPanel() {
            this.mWin = null;
            this.mWin = new Window("dialog", "Video Compress Settings", undefined, { resizeable: true });
            this.mWin.orientation = "column";
            var sizegr = this.mWin.add("panel", undefined, "Size Control");
            sizegr.alignment = ["fill", "top"];
            sizegr.orientation = "row";
            var widthgr = sizegr.add("group");
            widthgr.orientation = "row";
            widthgr.alignment = ["fill", "fill"];
            var widthlabel = widthgr.add("statictext", undefined, "Width:");
            widthlabel.alignment = ["left", "fill"];
            this.mWidth = widthgr.add("edittext", undefined, "540");
            this.mWidth.alignment = ["fill", "fill"];
            var heightgr = sizegr.add("group");
            heightgr.orientation = "row";
            heightgr.alignment = ["fill", "fill"];
            var heightlabel = heightgr.add("statictext", undefined, "Height:");
            heightlabel.alignment = ["left", "fill"];
            this.mHeight = heightgr.add("edittext", undefined, "960");
            this.mHeight.alignment = ["fill", "fill"];
            this.mLinkWidthHeight = sizegr.add("checkbox", undefined, "Link Width and Height");
            this.mLinkWidthHeight.value = true;
            this.mWidth.onChange = function () {
                if (self.mLinkWidthHeight.value) {
                    var width = parseInt(self.mWidth.text);
                    if (!isNaN(width) && width > 0) {
                        self.mHeight.text = (self.mVideoSource.height / (self.mVideoSource.width / width)).toString();
                    }
                }
            };
            this.mHeight.onChange = function () {
                if (self.mLinkWidthHeight.value) {
                    var height = parseInt(self.mHeight.text);
                    if (!isNaN(height) && height > 0) {
                        self.mWidth.text = (self.mVideoSource.width / (self.mVideoSource.height / height)).toString();
                    }
                }
            };
            var fpsgr = this.mWin.add("panel", undefined, "FPS Control");
            fpsgr.alignment = ["fill", "top"];
            fpsgr.orientation = "row";
            var fpslabel = fpsgr.add("statictext", undefined, "fps:");
            fpslabel.alignment = ["left", "center"];
            this.mFrameRate = fpsgr.add("edittext", undefined, "30");
            this.mFrameRate.alignment = ["fill", "fill"];
            var middlegr = this.mWin.add("group");
            middlegr.alignment = ["fill", "top"];
            middlegr.alignChildren = ["fill", "fill"];
            middlegr.orientation = "row";
            var bitratevaluegr = middlegr.add("panel", undefined, "BitRate Control");
            bitratevaluegr.orientation = "row";
            bitratevaluegr.alignment = ["fill", "fill"];
            var bitratelabel = bitratevaluegr.add("statictext", undefined, "bitrate(M/s):");
            bitratelabel.alignment = ["left", "fill"];
            this.mBitRatePreset = bitratevaluegr.add("dropdownlist", undefined, ["auto", "high", "medium", "low", "custom"]);
            this.mBitRatePreset.selection = 0;
            this.mBitRate = bitratevaluegr.add("edittext", undefined, "0");
            this.mBitRate.alignment = ["fill", "fill"];
            this.mBitRate.enabled = false;
            this.mBitRatePreset.onChange = function () {
                self.mBitRate.enabled = self.mBitRatePreset.selection == 3;
            };
            var gopgr = middlegr.add("panel", undefined, "I Frame Control");
            gopgr.orientation = "row";
            gopgr.alignment = ["right", "fill"];
            var goplabel = gopgr.add("statictext", undefined, "I Frame Interval:");
            goplabel.alignment = ["left", "fill"];
            this.mGopPreset = gopgr.add("dropdownlist", undefined, ["Auto", "4s", "2s", "1s", "0.5s", "0.2s", "All I Frame!"]);
            this.mGopPreset.selection = 0;
            var bottomgr = this.mWin.add("group");
            bottomgr.alignment = ["fill", "top"];
            bottomgr.alignChildren = ["fill", "fill"];
            bottomgr.orientation = "row";
            var alphagr = bottomgr.add("panel", undefined, "Alpha Control");
            alphagr.alignment = ["fill", "top"];
            alphagr.alignChildren = ["fill", "fill"];
            alphagr.orientation = "row";
            this.mReserveAlpha = alphagr.add("radiobutton", undefined, "Reserve Alpha");
            this.mDiscardAlpha = alphagr.add("radiobutton", undefined, "Discard Alpha");
            this.mDiscardAlpha.value = true;
            var extensiongr = bottomgr.add("panel", undefined, "File Type");
            extensiongr.alignment = ["fill", "top"];
            extensiongr.alignChildren = ["fill", "fill"];
            extensiongr.orientation = "row";
            this.mMovFileType = extensiongr.add("radiobutton", undefined, "MOV");
            this.mMp4FileType = extensiongr.add("radiobutton", undefined, "MP4");
            this.mMp4FileType.value = true;
            var actiongr = this.mWin.add("group");
            actiongr.alignment = ["fill", "top"];
            actiongr.alignChildren = ["fill", "top"];
            actiongr.orientation = "row";
            var self = this;
            var cancelBtn = actiongr.add("button", undefined, "Cancel");
            cancelBtn.onClick = function () {
                self.mAction = "Cancel";
                self.close();
            };
            var okBtn = actiongr.add("button", undefined, "OK");
            okBtn.onClick = function () {
                self.mAction = "OK";
                self.close();
            };
        }
        CompressVideoSourceSettingPanel.prototype.setVideoSource = function (video) {
            this.mVideoSource = video;
            this.mLinkWidthHeight.value = false;
            this.mWidth.text = video.width.toString();
            this.mHeight.text = video.height.toString();
            this.mLinkWidthHeight.value = true;
            this.mFrameRate.text = video.frameRate.toString();
            this.mBitRatePreset.selection = 0;
            this.mDiscardAlpha.value = true;
        };
        CompressVideoSourceSettingPanel.prototype.getIFrameInterval = function (fps) {
            var iframe = this.mGopPreset.selection;
            if (iframe > 0) {
                var gop = fps;
                if (iframe == 1) {
                    gop = Math.ceil(fps * 4);
                }
                else if (iframe == 2) {
                    gop = Math.ceil(fps * 2);
                }
                else if (iframe == 3) {
                    gop = Math.ceil(fps);
                }
                else if (iframe == 4) {
                    gop = Math.ceil(fps * 0.5);
                }
                else if (iframe == 5) {
                    gop = Math.ceil(fps * 0.2);
                }
                else if (iframe == 6) {
                    gop = 1;
                }
                return " -g " + gop + " -keyint_min 1";
            }
            return "";
        };
        CompressVideoSourceSettingPanel.prototype.getSettingCmd = function () {
            function checkFroNumber(control, title) {
                var value = parseInt(control.text);
                if (!isNaN(value)) {
                    if (value <= 0) {
                        alert(title + " value invalid! Please change!");
                        return null;
                    }
                    else {
                        return value;
                    }
                }
                else {
                    alert(title + " input is not a number! Please change!");
                    return null;
                }
            }
            var width = checkFroNumber(this.mWidth, "Width");
            if (width == null) {
                return null;
            }
            var height = checkFroNumber(this.mHeight, "Height");
            if (height == null) {
                return null;
            }
            var fps = checkFroNumber(this.mFrameRate, "FPS");
            if (fps == null) {
                return null;
            }
            var bitrate = 0;
            if (this.mBitRatePreset.selection == 4) {
                bitrate = checkFroNumber(this.mBitRate, "BitRate");
                if (bitrate == null) {
                    return null;
                }
            }
            var setting = "";
            if (width != this.mVideoSource.width || height != this.mVideoSource.height) {
                setting += " -s " + width + "x" + height;
            }
            if (fps != this.mVideoSource.frameRate) {
                setting += " -r " + fps;
            }
            setting += this.getIFrameInterval(fps);
            if (bitrate != 0) {
                setting += " -b:v " + bitrate + "M";
            }
            else {
                var preset = this.mBitRatePreset.selection;
                if (preset == 1) {
                    setting += " -preset medium";
                    setting += " -b:v " + FFUtils.CalculateBitrate(this.mVideoSource, 0.5) + "M";
                }
                else if (preset == 2) {
                    setting += " -preset medium";
                    setting += " -b:v " + FFUtils.CalculateBitrate(this.mVideoSource, 0.25) + "M";
                }
                else if (preset == 3) {
                    setting += " -preset fast";
                    setting += " -b:v " + FFUtils.CalculateBitrate(this.mVideoSource, 0.15) + "M";
                }
            }
            if (this.mMp4FileType.value) {
                setting += " mp4";
            }
            return setting;
        };
        CompressVideoSourceSettingPanel.prototype.alphaMode = function () {
            if (this.mVideoSource.mainSource.hasAlpha && this.mReserveAlpha.value) {
                return CompressVideoSourceSettingPanel.kReserveAlpha;
            }
            return CompressVideoSourceSettingPanel.kDiscardAlpha;
        };
        CompressVideoSourceSettingPanel.prototype.update = function () {
            this.mWin.layout.layout(true);
        };
        CompressVideoSourceSettingPanel.prototype.show = function () {
            this.mAction = "Cancel";
            var panel = this.mWin;
            panel.onResizing = panel.onResize = function () {
                panel.layout.resize();
            };
            panel.layout.layout(true);
            panel.layout.resize();
            panel.show();
        };
        CompressVideoSourceSettingPanel.prototype.close = function () {
            if (this.mWin) {
                this.mWin.close();
            }
        };
        CompressVideoSourceSettingPanel.kReserveAlpha = 0;
        CompressVideoSourceSettingPanel.kDiscardAlpha = 1;
        return CompressVideoSourceSettingPanel;
    }());
    var GIFSettingPanel = (function () {
        function GIFSettingPanel(makeThumbnail) {
            if (makeThumbnail === void 0) { makeThumbnail = false; }
            var self = this;
            this.mMakeThumbnail = makeThumbnail;
            this.mWin = new Window("dialog", "GIF Settings", undefined, { resizeable: true });
            this.mWin.orientation = "column";
            this.mWin.minimumSize[0] = 400;
            if (!this.mMakeThumbnail) {
                var fileGr = this.mWin.add("panel", undefined, "Video File");
                fileGr.orientation = "row";
                fileGr.alignment = ["fill", "top"];
                var fileLabel = fileGr.add("statictext", undefined, "Video File:");
                fileLabel.alignment = ["left", "center"];
                this.mFilePath = fileGr.add("edittext", undefined, "", { readonly: true });
                this.mFilePath.alignment = ["fill", "center"];
                this.mSelectFile = fileGr.add("button", undefined, "...");
                this.mSelectFile.alignment = ["right", "center"];
                this.mSelectFile.onClick = function () {
                    self.selectVideoFile();
                };
            }
            var outputGr = this.mWin.add("panel", undefined, "Output GIF File");
            outputGr.orientation = "row";
            outputGr.alignment = ["fill", "top"];
            var outputLabel = outputGr.add("statictext", undefined, "Output File:");
            outputLabel.alignment = ["left", "center"];
            this.mOutputPath = outputGr.add("edittext", undefined, "", { readonly: true });
            this.mOutputPath.alignment = ["fill", "center"];
            this.mSelectOutput = outputGr.add("button", undefined, "...");
            this.mSelectOutput.alignment = ["right", "center"];
            this.mSelectOutput.onClick = function () {
                self.selectGIFFile();
            };
            var settingGr = this.mWin.add("panel", undefined, "Settings");
            settingGr.orientation = "row";
            settingGr.alignment = ["fill", "top"];
            var scaleGr = settingGr.add("group");
            scaleGr.orientation = "row";
            scaleGr.alignment = ["fill", "fill"];
            var scaleLabel = scaleGr.add("statictext", undefined, "Scale:");
            scaleLabel.alignment = ["left", "center"];
            this.mScale = scaleGr.add("dropdownlist", undefined, ["100%", "75%", "50%", "25%", "10%"]);
            this.mScale.alignment = ["fill", "center"];
            this.mScale.selection = 2;
            var fpsGr = settingGr.add("group");
            fpsGr.orientation = "row";
            fpsGr.alignment = ["fill", "fill"];
            var fpsLabel = fpsGr.add("statictext", undefined, "FPS:");
            fpsLabel.alignment = ["left", "center"];
            this.mFps = fpsGr.add("dropdownlist", undefined, ["100%", "75%", "50%", "25%", "10%"]);
            this.mFps.alignment = ["fill", "center"];
            this.mFps.selection = 2;
            var speedGr = settingGr.add("group");
            speedGr.orientation = "row";
            speedGr.alignment = ["fill", "fill"];
            var speedLabel = speedGr.add("statictext", undefined, "Speed:");
            speedLabel.alignment = ["left", "center"];
            this.mSpeed = speedGr.add("dropdownlist", undefined, ["50%", "100%", "200%", "300%", "400%"]);
            this.mSpeed.alignment = ["fill", "center"];
            this.mSpeed.selection = 1;
            this.mConvert = this.mWin.add("button", undefined, this.mMakeThumbnail ? "Make" : "Convert");
            this.mConvert.alignment = ["fill", "top"];
            this.mConvert.onClick = function () {
                if (self.mMakeThumbnail) {
                    var comp = DomUtils.GetCurrentComp();
                    if (comp == null) {
                        alert("Please select the comp you want to render!");
                    }
                    else {
                        self.mAction = "OK";
                        self.close();
                    }
                }
                else {
                    self.mAction = "OK";
                    self.close();
                }
            };
        }
        GIFSettingPanel.prototype.selectVideoFile = function () {
            var f = File.openDialog("", "Video file:*.mp4;*.MP4;*.mov;*.MOV;*.avi;*.AVI", false);
            if (f && f.exists) {
                this.mFilePath.text = f.fsName;
            }
        };
        GIFSettingPanel.prototype.selectGIFFile = function () {
            var f = File.saveDialog("Output GIF file", "GIF file:*.gif");
            if (f) {
                var dotIdx = f.displayName.lastIndexOf(".");
                if (dotIdx == -1 || f.displayName.substr(dotIdx).toLocaleLowerCase() != ".gif") {
                    this.mOutputPath.text = f.fsName + ".gif";
                }
                else {
                    this.mOutputPath.text = f.fsName;
                }
            }
        };
        GIFSettingPanel.prototype.update = function () {
            this.mWin.layout.layout(true);
        };
        GIFSettingPanel.prototype.show = function () {
            this.mAction = "Cancel";
            var panel = this.mWin;
            panel.onResizing = panel.onResize = function () {
                panel.layout.resize();
            };
            panel.layout.layout(true);
            panel.layout.resize();
            panel.show();
        };
        GIFSettingPanel.prototype.close = function () {
            if (this.mWin) {
                this.mWin.close();
            }
        };
        GIFSettingPanel.ConvertIndexToPercent = function (index) {
            switch (index) {
                case 0: return 1.0;
                case 1: return 0.75;
                case 2: return 0.5;
                case 3: return 0.25;
                case 4: return 0.1;
                default: return 1.0;
            }
        };
        GIFSettingPanel.ConvertIndexToScale = function (index) {
            switch (index) {
                case 0: return 0.5;
                case 1: return 1.0;
                case 2: return 2.0;
                case 3: return 3.0;
                case 4: return 4.0;
                default: return 1.0;
            }
        };
        GIFSettingPanel.prototype.composeCmd = function (inputFile) {
            if (inputFile === void 0) { inputFile = ""; }
            if (inputFile == undefined || inputFile.length == 0) {
                inputFile = this.mFilePath.text;
            }
            inputFile = inputFile.replace(/\\/g, "\/");
            var outputFile = this.mOutputPath.text.replace(/\\/g, "\/");
            var inputFileObj = new File(inputFile);
            if (!inputFileObj.exists) {
                alert(VECleaner.kTranslator.mData.HOST_AssetTools_GIF2Video_SetVideo);
                return "";
            }
            var ffpath = FFUtils.GetFFmpegBinary();
            ffpath = ffpath.replace(/\\/g, "\/");
            ffpath = ffpath.replace(/%20/g, "\ ");
            var fps = 20;
            var speed = GIFSettingPanel.ConvertIndexToScale(this.mSpeed.selection.index);
            var width = 320;
            var height = 320;
            if ((new File(ffpath)).exists && inputFileObj.exists) {
                var inputFileItem = DomUtils.GetItemByFile(inputFileObj);
                if (inputFileItem == null) {
                    var impOpt = new ImportOptions(inputFileObj);
                    inputFileItem = app.project.importFile(impOpt);
                    fps = Math.round(inputFileItem.frameRate * GIFSettingPanel.ConvertIndexToPercent(this.mFps.selection.index));
                    width = Math.round(inputFileItem.width * GIFSettingPanel.ConvertIndexToPercent(this.mScale.selection.index));
                    height = Math.round(inputFileItem.height * GIFSettingPanel.ConvertIndexToPercent(this.mScale.selection.index));
                    inputFileItem.remove();
                }
                else {
                    fps = Math.round(inputFileItem.frameRate * GIFSettingPanel.ConvertIndexToPercent(this.mFps.selection.index));
                    width = Math.round(inputFileItem.width * GIFSettingPanel.ConvertIndexToPercent(this.mScale.selection.index));
                    height = Math.round(inputFileItem.height * GIFSettingPanel.ConvertIndexToPercent(this.mScale.selection.index));
                }
                var paletteFilePath = Settings.NewCacheAsset(Settings.NewCacheAssetName(".png"));
                var paletteCmd = '"' + ffpath + '" -i "' + inputFile + '" -r ' + fps + ' -vf fps=' + fps + ',scale=' + Math.min(width, height) + ':-1:flags=lanczos,palettegen -y "' + paletteFilePath + '" ';
                var gifCmd = '"' + ffpath + '" -i "' + inputFile + '" -i "' + paletteFilePath + '" -r ' + fps + ' -lavfi fps=' + fps + ',scale=' + Math.min(width, height) + ':-1:flags=lanczos[x];[x]setpts=' + (1.0 / speed) + '*PTS[y];[y][1:v]paletteuse -y "' + outputFile + '" ';
                var json = new JsonWriter();
                json.startObject();
                json.putKey("cmds");
                json.startArray();
                json.putString(paletteCmd);
                json.putString(gifCmd);
                json.endArray();
                json.putKey("file");
                json.putString(inputFile);
                json.endObject();
                return json.getContent();
            }
            else {
                return "";
            }
        };
        return GIFSettingPanel;
    }());
    var CompressPNGSettingPanel = (function () {
        function CompressPNGSettingPanel(fromFile) {
            var self = this;
            this.mWin = new Window("dialog", "Convert PNG Settings", undefined, { resizeable: true });
            this.mWin.orientation = "column";
            this.mWin.minimumSize[0] = 400;
            this.mFromVideoFile = fromFile;
            this.mVideoSource = null;
            if (this.mFromVideoFile) {
                var fileGr = this.mWin.add("panel", undefined, "Video File");
                fileGr.orientation = "row";
                fileGr.alignment = ["fill", "top"];
                var fileLabel = fileGr.add("statictext", undefined, "Video File:");
                fileLabel.alignment = ["left", "center"];
                this.mFilePath = fileGr.add("edittext", undefined, "", { readonly: true });
                this.mFilePath.alignment = ["fill", "center"];
                this.mSelectFile = fileGr.add("button", undefined, "...");
                this.mSelectFile.alignment = ["right", "center"];
                this.mSelectFile.onClick = function () {
                    self.selectVideoFile();
                };
            }
            var outputGr = this.mWin.add("panel", undefined, "Output PNG Folder");
            outputGr.orientation = "row";
            outputGr.alignment = ["fill", "top"];
            var outputLabel = outputGr.add("statictext", undefined, "Output File:");
            outputLabel.alignment = ["left", "center"];
            this.mCompressPNG = this.mWin.add("checkbox", undefined, VECleaner.kTranslator.mData.HOST_AssetTools_OptimizePNG_SetGIF);
            this.mOutputPath = outputGr.add("edittext", undefined, "", { readonly: true });
            this.mOutputPath.alignment = ["fill", "center"];
            this.mSelectOutput = outputGr.add("button", undefined, "...");
            this.mSelectOutput.alignment = ["right", "center"];
            this.mSelectOutput.onClick = function () {
                self.selectPngFolder();
            };
            this.mConvert = this.mWin.add("button", undefined, "Convert");
            this.mConvert.alignment = ["fill", "top"];
            this.mConvert.onClick = function () {
                if (!self.mFromVideoFile) {
                    var comp = DomUtils.GetCurrentComp();
                    if (comp == null) {
                        alert("Please select the comp you want to render!");
                    }
                    else {
                        self.mAction = "OK";
                        self.close();
                    }
                }
                else {
                    self.mAction = "OK";
                    self.close();
                }
            };
        }
        CompressPNGSettingPanel.prototype.selectVideoFile = function () {
            var f = File.openDialog("", "Video file:*.mp4;*.MP4;*.mov;*.MOV;*.avi;*.AVI", false);
            if (f && f.exists) {
                this.mFilePath.text = f.fsName;
            }
        };
        CompressPNGSettingPanel.prototype.selectPngFolder = function () {
            var folder = Folder.selectDialog("Select the folder to save your png files");
            if (folder) {
                this.mOutputPath.text = folder.fsName;
            }
        };
        CompressPNGSettingPanel.prototype.setVideoSource = function (video) {
            this.mVideoSource = video;
        };
        CompressPNGSettingPanel.prototype.composeCmd = function () {
            if (this.mOutputPath.text.length > 0) {
                if (!this.mFromVideoFile && this.mVideoSource && this.mVideoSource.frameRate > 0) {
                    var videoFileName = this.mVideoSource.file.displayName;
                    var index = videoFileName.lastIndexOf(".");
                    if (index == videoFileName.length - 4) {
                        videoFileName = videoFileName.substr(0, videoFileName.length - 4);
                    }
                    else {
                        videoFileName = Settings.NewCacheAssetName("");
                    }
                    var cmd = FFUtils.CreatePNGSequenceCommans(this.mVideoSource.file.fsName, this.mOutputPath.text, videoFileName);
                    var json = new JsonWriter();
                    json.startObject();
                    json.putKey("cmds");
                    json.startArray();
                    json.putString(cmd);
                    if (this.mCompressPNG.value) {
                        json.putString("pngquant_nofile:" + PNGQuantUtil.CreateCompressCmdsWithoutFiles());
                    }
                    json.endArray();
                    json.putKey("folder");
                    json.putString(this.mOutputPath.text);
                    json.putKey("name");
                    json.putString(videoFileName);
                    json.putKey("replace");
                    json.putNumber(this.mVideoSource.id);
                    json.endObject();
                    return json.getContent();
                }
                else if (this.mFromVideoFile && this.mFilePath.text.length > 0) {
                    var videoFile = new File(this.mFilePath.text);
                    var videoFileName = videoFile.displayName;
                    var index = videoFileName.lastIndexOf(".");
                    if (index == videoFileName.length - 4) {
                        videoFileName = videoFileName.substr(0, videoFileName.length - 4);
                    }
                    else {
                        videoFileName = Settings.NewCacheAssetName("");
                    }
                    var cmd = FFUtils.CreatePNGSequenceCommans(videoFile.fsName, this.mOutputPath.text, videoFileName);
                    var json = new JsonWriter();
                    json.startObject();
                    json.putKey("cmds");
                    json.startArray();
                    json.putString(cmd);
                    json.putString("pngquant_nofile:" + PNGQuantUtil.CreateCompressCmdsWithoutFiles());
                    json.endArray();
                    json.putKey("folder");
                    json.putString(this.mOutputPath.text);
                    json.putKey("name");
                    json.putString(videoFileName);
                    json.endObject();
                    return json.getContent();
                }
            }
            return "";
        };
        CompressPNGSettingPanel.prototype.update = function () {
            this.mWin.layout.layout(true);
        };
        CompressPNGSettingPanel.prototype.show = function () {
            this.mAction = "Cancel";
            var panel = this.mWin;
            panel.onResizing = panel.onResize = function () {
                panel.layout.resize();
            };
            panel.layout.layout(true);
            panel.layout.resize();
            panel.show();
        };
        CompressPNGSettingPanel.prototype.close = function () {
            if (this.mWin) {
                this.mWin.close();
            }
        };
        return CompressPNGSettingPanel;
    }());
    var AssetTools = (function () {
        function AssetTools() {
        }
        AssetTools.HandlePremultipliedAlphaVideo = function () {
            var comp = DomUtils.GetCurrentComp();
            if (comp != null) {
                var shouldDoIt = confirm(VECleaner.kTranslator.format(VECleaner.kTranslator.mData.HOST_AssetTools_HandlePremultipliedAlphaVideo_msg1, comp.name), false, VECleaner.kTranslator.mData.HOST_AssetTools_HandlePremultipliedAlphaVideo_msg2);
                if (shouldDoIt) {
                    for (var l = 1; l <= comp.numLayers; l++) {
                        var layer = comp.layer(l);
                        var layerTypes = LayerTypeUtils.GetlayerType(layer);
                        if (layerTypes & LayerTypes.kVideoLayer) {
                            var layerSource = layer.source;
                            var videoFootage = layerSource.mainSource;
                            var alphaType = videoFootage.alphaMode;
                            if (videoFootage.hasAlpha && alphaType == AlphaMode.PREMULTIPLIED) {
                                Settings.WriteLogContent("Begin convert layer:" + l.toString() + " Name:" + layer.name + " source file to straight alpha mode");
                                var tempComp = app.project.items.addComp(videoFootage.file.displayName, layerSource.width, layerSource.height, 1, layerSource.duration, layerSource.frameRate);
                                tempComp.layers.add(layerSource);
                                var newfile = Settings.NewCacheAsset(Settings.NewCacheAssetName(".mov"));
                                RenderUtils.RenderComp(tempComp, RenderUtils.kStraightAlphaVideoRenderTemplate, newfile);
                                layerSource.replace(new File(newfile));
                                tempComp.remove();
                                Settings.WriteLogContent("End convert alpha");
                            }
                        }
                    }
                    alert(VECleaner.kTranslator.mData.HOST_AssetTools_HandlePremultipliedAlphaVideo_msg3);
                }
            }
            else {
                alert(VECleaner.kTranslator.mData.HOST_AssetTools_HandlePremultipliedAlphaVideo_msg4);
                return false;
            }
            return true;
        };
        AssetTools.HandleNonSquarePixelItems = function () {
            var shouldDoIt = confirm(VECleaner.kTranslator.mData.HOST_AssetTools_HandleNonSquarePixelItems_msg1, false, VECleaner.kTranslator.mData.HOST_AssetTools_HandleNonSquarePixelItems_msg2);
            if (shouldDoIt) {
                PixelAspectHandler.HandleProjectItems();
                alert(VECleaner.kTranslator.mData.HOST_AssetTools_HandleNonSquarePixelItems_msg3);
            }
            return true;
        };
        AssetTools.CompressVideoSourceWithAlphaStepOne = function (selectedItem, extraSetting) {
            if (selectedItem === void 0) { selectedItem = null; }
            if (extraSetting === void 0) { extraSetting = ""; }
            if (selectedItem == null) {
                var layer = DomUtils.GetFirstSelectedLayer();
                if (layer && layer instanceof AVLayer && layer.source instanceof FootageItem && layer.source.frameRate > 0 && layer.source.mainSource.file != null) {
                    var ret = confirm(VECleaner.kTranslator.format(VECleaner.kTranslator.mData.HOST_AssetTools_CompressVideoSourceWithAlpha_msg1, layer.source.mainSource.file.fsName), false, VECleaner.kTranslator.mData.HOST_AssetTools_CompressVideoSourceWithAlpha_msg2);
                    if (ret) {
                        selectedItem = layer.source;
                    }
                    else {
                        alert(VECleaner.kTranslator.mData.HOST_AssetTools_CompressVideoSourceWithAlpha_msg4);
                    }
                }
                else {
                    var item = DomUtils.GetCurrentItem();
                    if (item instanceof FootageItem && item.frameRate > 0 && item.mainSource.file != null) {
                        var ret = confirm(VECleaner.kTranslator.format(VECleaner.kTranslator.mData.HOST_AssetTools_CompressVideoSourceWithAlpha_msg1, item.mainSource.file.fsName), false, VECleaner.kTranslator.mData.HOST_AssetTools_CompressVideoSourceWithAlpha_msg2);
                        if (ret) {
                            selectedItem = item;
                        }
                    }
                    else {
                        alert(VECleaner.kTranslator.mData.HOST_AssetTools_CompressVideoSourceWithAlpha_msg4);
                    }
                }
            }
            if (selectedItem) {
                if (selectedItem.width % 2 != 0 || selectedItem.height % 2 != 0) {
                    alert(VECleaner.kTranslator.mData.HOST_AssetTools_VideoOddSizeError);
                }
                else {
                    if (selectedItem.mainSource.hasAlpha) {
                        return TransparentVideoHandler.CompressAlphaVideoStepOne(selectedItem, extraSetting);
                    }
                    else {
                        return TransparentVideoHandler.CompressNormalVideoStepOne(selectedItem, extraSetting);
                    }
                }
            }
            return "";
        };
        AssetTools.CompressVideoSourceWithAlphaStepTwo = function (cmd) {
            if (cmd.length > 0) {
                var cmdData = JSON.parse(cmd);
                if (cmdData.output && cmdData.replace && typeof (cmdData.matte) == "undefined") {
                    TransparentVideoHandler.CompressNormalVideoStepTwo(cmd);
                }
                else {
                    TransparentVideoHandler.CompressAlphaVideoStepTwo(cmd);
                }
                alert(VECleaner.kTranslator.mData.HOST_AssetTools_CompressVideoSourceWithAlpha_msg3);
                return true;
            }
            return false;
        };
        AssetTools.CompressVideoSourceWithoutAlphaStepOne = function (selectedItem, extraSetting) {
            if (selectedItem === void 0) { selectedItem = null; }
            if (extraSetting === void 0) { extraSetting = ""; }
            if (selectedItem == null) {
                var layer = DomUtils.GetFirstSelectedLayer();
                if (layer && layer instanceof AVLayer && layer.source instanceof FootageItem && layer.source.frameRate > 0 && layer.source.mainSource.file != null) {
                    var ret = confirm(VECleaner.kTranslator.format(VECleaner.kTranslator.mData.HOST_AssetTools_CompressVideoSourceWithoutAlpha_msg1, layer.source.mainSource.file.fsName), false, VECleaner.kTranslator.mData.HOST_AssetTools_CompressVideoSourceWithoutAlpha_msg2);
                    if (ret) {
                        selectedItem = layer.source;
                    }
                }
                else {
                    var item = DomUtils.GetCurrentItem();
                    if (item instanceof FootageItem && item.frameRate > 0 && item.mainSource.file != null) {
                        var ret = confirm(VECleaner.kTranslator.format(VECleaner.kTranslator.mData.HOST_AssetTools_CompressVideoSourceWithoutAlpha_msg1, item.mainSource.file.fsName), false, VECleaner.kTranslator.mData.HOST_AssetTools_CompressVideoSourceWithoutAlpha_msg2);
                        if (ret) {
                            selectedItem = item;
                        }
                    }
                    else {
                        alert(VECleaner.kTranslator.mData.HOST_AssetTools_CompressVideoSourceWithoutAlpha_msg4);
                    }
                }
            }
            if (selectedItem) {
                if (selectedItem.width % 2 != 0 || selectedItem.height % 2 != 0) {
                    alert(VECleaner.kTranslator.mData.HOST_AssetTools_VideoOddSizeError);
                }
                else {
                    return TransparentVideoHandler.CompressNormalVideoStepOne(selectedItem, extraSetting);
                }
            }
            return "";
        };
        AssetTools.CompressVideoSourceWithoutAlphaStepTwo = function (cmd) {
            if (cmd.length > 0) {
                TransparentVideoHandler.CompressNormalVideoStepTwo(cmd);
                alert(VECleaner.kTranslator.mData.HOST_AssetTools_CompressVideoSourceWithoutAlpha_msg3);
                return true;
            }
            return false;
        };
        AssetTools.CompressVideoSourceAdvance = function () {
            var selectedItem = null;
            if (selectedItem == null) {
                var layer = DomUtils.GetFirstSelectedLayer();
                if (layer && layer instanceof AVLayer && layer.source instanceof FootageItem && layer.source.frameRate > 0 && layer.source.mainSource.file != null) {
                    selectedItem = layer.source;
                }
                else {
                    var item = DomUtils.GetCurrentItem();
                    if (item instanceof FootageItem && item.frameRate > 0 && item.mainSource.file != null) {
                        selectedItem = item;
                    }
                    else {
                        alert(VECleaner.kTranslator.mData.HOST_AssetTools_CompressVideoSourceWithAlpha_msg4);
                    }
                }
            }
            if (selectedItem) {
                if (selectedItem.width % 2 != 0 || selectedItem.height % 2 != 0) {
                    alert(VECleaner.kTranslator.mData.HOST_AssetTools_VideoOddSizeError);
                }
                else {
                    if (AssetTools.kVideoCompressSettingWin) {
                        AssetTools.kVideoCompressSettingWin.close();
                        AssetTools.kVideoCompressSettingWin = null;
                    }
                    AssetTools.kVideoCompressSettingWin = new CompressVideoSourceSettingPanel();
                    AssetTools.kVideoCompressSettingWin.setVideoSource(selectedItem);
                    AssetTools.kVideoCompressSettingWin.show();
                    if (AssetTools.kVideoCompressSettingWin.mAction == "OK") {
                        if (AssetTools.kVideoCompressSettingWin.alphaMode() != CompressVideoSourceSettingPanel.kDiscardAlpha) {
                            return AssetTools.CompressVideoSourceWithAlphaStepOne(selectedItem, AssetTools.kVideoCompressSettingWin.getSettingCmd());
                        }
                        else {
                            return AssetTools.CompressVideoSourceWithoutAlphaStepOne(selectedItem, AssetTools.kVideoCompressSettingWin.getSettingCmd());
                        }
                    }
                }
            }
            else {
                alert(VECleaner.kTranslator.mData.HOST_AssetTools_CompressVideoSourceWithAlpha_msg4);
            }
            return "";
        };
        AssetTools.CompressVideoSourceAdvanceStepTwo = function (cmd) {
            AssetTools.CompressVideoSourceWithAlphaStepTwo(cmd);
        };
        AssetTools.CreateGifFromVideo = function () {
            if (AssetTools.kGIFSettingWin) {
                AssetTools.kGIFSettingWin.close();
                AssetTools.kGIFSettingWin = null;
            }
            AssetTools.kGIFSettingWin = new GIFSettingPanel();
            AssetTools.kGIFSettingWin.show();
            if (AssetTools.kGIFSettingWin.mAction == "OK") {
                return AssetTools.kGIFSettingWin.composeCmd();
            }
            return "";
        };
        AssetTools.CreateGifFromVideo2 = function (cmd) {
            if (cmd.length > 0) {
                alert(VECleaner.kTranslator.mData.HOST_AssetTools_GIF2Video_Success);
            }
            else {
                alert(VECleaner.kTranslator.mData.HOST_AssetTools_GIF2Video_Fail);
            }
        };
        AssetTools.CreatePNGSequenceFromLayer = function () {
            var selectedItem = null;
            var layer = DomUtils.GetFirstSelectedLayer();
            if (layer && layer instanceof AVLayer && layer.source instanceof FootageItem && layer.source.frameRate > 0 && layer.source.mainSource.file != null) {
                selectedItem = layer.source;
            }
            else {
                var item = DomUtils.GetCurrentItem();
                if (item instanceof FootageItem && item.frameRate > 0 && item.mainSource.file != null) {
                    selectedItem = item;
                }
                else {
                    alert(VECleaner.kTranslator.mData.HOST_AssetTools_CompressVideoSourceWithAlpha_msg4);
                }
            }
            if (selectedItem) {
                if (AssetTools.kPNGSettingWin) {
                    AssetTools.kPNGSettingWin.close();
                    AssetTools.kPNGSettingWin = null;
                }
                AssetTools.kPNGSettingWin = new CompressPNGSettingPanel(false);
                AssetTools.kPNGSettingWin.setVideoSource(selectedItem);
                AssetTools.kPNGSettingWin.show();
                if (AssetTools.kPNGSettingWin.mAction == "OK") {
                    return AssetTools.kPNGSettingWin.composeCmd();
                }
            }
            else {
                alert(VECleaner.kTranslator.mData.HOST_AssetTools_CompressVideoSourceWithAlpha_msg4);
            }
            return "";
        };
        AssetTools.CreatePNGSequenceFromVideoFile = function () {
            if (AssetTools.kPNGSettingWin) {
                AssetTools.kPNGSettingWin.close();
                AssetTools.kPNGSettingWin = null;
            }
            AssetTools.kPNGSettingWin = new CompressPNGSettingPanel(true);
            AssetTools.kPNGSettingWin.show();
            if (AssetTools.kPNGSettingWin.mAction == "OK") {
                return AssetTools.kPNGSettingWin.composeCmd();
            }
            return "";
        };
        AssetTools.CreatePNGSequenceFromVideo2 = function (cmd) {
            if (cmd.length > 0) {
                var cmdData = JSON.parse(cmd);
                if (cmdData.folder && cmdData.name && cmdData.replace) {
                    var firstPNGPath = cmdData.folder + "/" + cmdData.name + "_00001.png";
                    var videoFootage = DomUtils.GetItemById(cmdData.replace);
                    videoFootage.replaceWithSequence(new File(firstPNGPath), true);
                }
                alert(VECleaner.kTranslator.mData.HOST_AssetTools_CompressVideoSourceWithAlpha_msg3);
                return true;
            }
            return true;
        };
        AssetTools.RemoveUnusedVideoFiles = function () {
            var shouldDoIt = confirm(VECleaner.kTranslator.mData.HOST_AssetTools_RemoveUnusedVideoFiles_msg2, false, VECleaner.kTranslator.mData.HOST_AssetTools_RemoveUnusedVideoFiles_msg1);
            if (shouldDoIt) {
                var num = app.project.numItems;
                var unusedFiles = [];
                for (var i = 1; i <= num; i++) {
                    var item = app.project.item(i);
                    if (item instanceof FootageItem && item.usedIn.length == 0 && item.mainSource && item.mainSource.file) {
                        var fileName = item.mainSource.file.displayName.toLocaleLowerCase();
                        if (fileName.lastIndexOf(".mov") != -1 || fileName.lastIndexOf(".mp4") != -1) {
                            unusedFiles.push(item.mainSource.file.fsName);
                            item.remove();
                            num = app.project.numItems;
                        }
                    }
                }
                var shouldDel = confirm(VECleaner.kTranslator.format(VECleaner.kTranslator.mData.HOST_AssetTools_RemoveUnusedVideoFiles_msg4, unusedFiles.length.toString()), false, VECleaner.kTranslator.mData.HOST_AssetTools_RemoveUnusedVideoFiles_msg1);
                if (shouldDel) {
                    var currentProj = app.project;
                    if (currentProj) {
                        currentProj.save();
                        var tempFile = currentProj.file;
                        app.newProject();
                        for (var f = 0; f < unusedFiles.length; f++) {
                            (new File(unusedFiles[f])).remove();
                        }
                        app.open(tempFile);
                    }
                }
                alert(VECleaner.kTranslator.mData.HOST_AssetTools_RemoveUnusedVideoFiles_msg3);
            }
            return true;
        };
        AssetTools.kVideoCompressSettingWin = null;
        AssetTools.kGIFSettingWin = null;
        AssetTools.kPNGSettingWin = null;
        return AssetTools;
    }());
    var SimpleItemListWindow = (function () {
        function SimpleItemListWindow(title, numColums, titles) {
            this.mWin = null;
            this.mWin = new Window("palette", title, undefined, { resizeable: true });
            this.mWin.orientation = "column";
            this.mWin.maximumSize.width = 1000;
            this.mWin.maximumSize.height = 1400;
            this.mList = numColums > 0 ? this.mWin.add("listbox", undefined, undefined, { numberOfColumns: numColums, showHeaders: true, columnTitles: titles }) : this.mWin.add("listbox", undefined, undefined);
            ;
            this.mList.alignment = ["fill", "fill"];
        }
        SimpleItemListWindow.prototype.addShowButton = function (title, callBack) {
            if (this.mShowSelection == null) {
                this.mShowSelection = this.mWin.add("button", undefined, title);
                this.mShowSelection.alignment = ["fill", "bottom"];
                this.update();
            }
            else {
                this.mShowSelection.text = title;
            }
            this.mShowSelection.onClick = callBack;
        };
        SimpleItemListWindow.prototype.removeItems = function () {
            if (this.mList) {
                this.mList.removeAll();
                this.update();
            }
        };
        SimpleItemListWindow.prototype.update = function () {
            this.mWin.layout.layout(true);
        };
        SimpleItemListWindow.prototype.show = function () {
            var panel = this.mWin;
            panel.onResizing = panel.onResize = function () {
                panel.layout.resize();
            };
            panel.layout.layout(true);
            panel.layout.resize();
            panel.show();
        };
        SimpleItemListWindow.prototype.close = function () {
            if (this.mWin) {
                this.removeItems();
                this.mWin.close();
            }
        };
        return SimpleItemListWindow;
    }());
    var SearchTools = (function () {
        function SearchTools() {
        }
        SearchTools.FindUnsupportedTextAnimators = function () {
        };
        SearchTools.FindTimeReamppingLayer = function () {
        };
        SearchTools.FindBigVideoFiles = function () {
            var VideoExtensions = [".mov", ".mp4", ".avi", ".wmv", ".ts", ".3gp", ".m4v"];
            var fileSizeStr = prompt(VECleaner.kTranslator.mData.HOST_SearchTools_FindBigVideoFiles_msg1, "20", VECleaner.kTranslator.mData.HOST_SearchTools_FindBigVideoFiles_msg2);
            var fileSize = parseFloat(fileSizeStr);
            var bigFiles = [];
            if (!isNaN(fileSize) && fileSize > 1) {
                for (var i = 1; i <= app.project.numItems; i++) {
                    var footage = app.project.item(i);
                    if (footage instanceof FootageItem) {
                        var file = footage.mainSource.file;
                        if (file) {
                            var idx = file.name.lastIndexOf(".");
                            var ext = file.name.substr(idx, file.name.length - idx);
                            if (ArrayUtils.DoesArrayContain(VideoExtensions, ext)) {
                                var size = file.length / 1024.0 / 1024.0;
                                if (size > fileSize) {
                                    bigFiles.push(footage);
                                }
                            }
                        }
                    }
                }
            }
            if (bigFiles.length > 0) {
                if (SearchTools.kBigVideoFileWindow) {
                    SearchTools.kBigVideoFileWindow.close();
                    SearchTools.kBigVideoFileWindow = null;
                }
                if (SearchTools.kBigVideoFileWindow == null) {
                    SearchTools.kBigVideoFileWindow = new SimpleItemListWindow(VECleaner.kTranslator.mData.HOST_SearchTools_FindBigVideoFiles_msg3, 2, [VECleaner.kTranslator.mData.HOST_SearchTools_FindBigVideoFiles_msg4, VECleaner.kTranslator.mData.HOST_SearchTools_FindBigVideoFiles_msg5]);
                }
                bigFiles.sort(function (a, b) {
                    return b.mainSource.file.length - a.mainSource.file.length;
                });
                for (var g = 0; g < bigFiles.length; g++) {
                    var row = SearchTools.kBigVideoFileWindow.mList.add("item", bigFiles[g].mainSource.file.displayName);
                    var size = bigFiles[g].mainSource.file.length / 1024.0 / 1024.0;
                    row.subItems[0].text = size < 1024 ? (size.toFixed(2) + "M") : ((size / 1024.0).toFixed(2) + "G");
                }
                SearchTools.kBigVideoFileWindow.addShowButton(VECleaner.kTranslator.mData.HOST_SearchTools_FindBigVideoFiles_msg6, function () {
                    var selection = SearchTools.kBigVideoFileWindow.mList.selection;
                    if (selection != null) {
                        var footage = bigFiles[selection.index];
                        DomUtils.ShowItem(footage.id);
                    }
                });
                SearchTools.kBigVideoFileWindow.show();
            }
            else {
                alert(VECleaner.kTranslator.mData.HOST_SearchTools_FindBigVideoFiles_msg7);
                return false;
            }
            return true;
        };
        SearchTools.Find3DLayers = function () {
            var comp = DomUtils.GetCurrentComp();
            if (comp != null) {
                if (SearchTools.k3DLayerWindow) {
                    SearchTools.k3DLayerWindow.close();
                    SearchTools.k3DLayerWindow = null;
                }
                if (SearchTools.k3DLayerWindow == null) {
                    SearchTools.k3DLayerWindow = new SimpleItemListWindow(VECleaner.kTranslator.mData.HOST_SearchTools_Find3DLayers_msg1, 3, [VECleaner.kTranslator.mData.HOST_SearchTools_Find3DLayers_msg2, VECleaner.kTranslator.mData.HOST_SearchTools_Find3DLayers_msg3, VECleaner.kTranslator.mData.HOST_SearchTools_Find3DLayers_msg4]);
                }
                var threeDLayerHandle_1 = new ThreeDLayerHandler(comp);
                if (threeDLayerHandle_1.empty()) {
                    alert(VECleaner.kTranslator.mData.HOST_SearchTools_Find3DLayers_msg5);
                }
                else {
                    for (var i = 0; i < threeDLayerHandle_1.mAllComps.length; i++) {
                        var comp_2 = threeDLayerHandle_1.mAllComps[i];
                        if (!comp_2.empty()) {
                            for (var g = 0; g < comp_2.mGroups.length; g++) {
                                var row = SearchTools.k3DLayerWindow.mList.add("item", comp_2.mComp.name);
                                row.subItems[0].text = comp_2.mGroups[g].mStartIndex.toString();
                                row.subItems[1].text = comp_2.mGroups[g].mCount.toString();
                                comp_2.mGroups[g].mUIIdx = row.index;
                            }
                        }
                    }
                    SearchTools.k3DLayerWindow.addShowButton(VECleaner.kTranslator.mData.HOST_SearchTools_Find3DLayers_msg6, function () {
                        if (SearchTools.k3DLayerWindow.mList.selection != null) {
                            CompCleaner.ClearSelection(threeDLayerHandle_1.mMainComp);
                            var sel = SearchTools.k3DLayerWindow.mList.selection.index;
                            threeDLayerHandle_1.selectAt(sel);
                        }
                    });
                    SearchTools.k3DLayerWindow.show();
                }
            }
            else {
                alert(VECleaner.kTranslator.mData.HOST_SearchTools_Find3DLayers_msg7);
                return false;
            }
            return true;
        };
        SearchTools.FindUnsupportedBlendMode = function () {
            var comp = DomUtils.GetCurrentComp();
            if (comp != null) {
                var blendModeHandler_1 = new UnsupportedBlendModeHandler(comp);
                if (blendModeHandler_1.mAllComps.length == 0) {
                    alert(VECleaner.kTranslator.mData.HOST_SearchTools_FindUnsupportedBlendMode_msg1);
                    return true;
                }
                else {
                    if (SearchTools.kBlendModeWindow) {
                        SearchTools.kBlendModeWindow.close();
                        SearchTools.kBlendModeWindow = null;
                    }
                    if (SearchTools.kBlendModeWindow == null) {
                        SearchTools.kBlendModeWindow = new SimpleItemListWindow(VECleaner.kTranslator.mData.HOST_SearchTools_FindUnsupportedBlendMode_msg2, 3, [VECleaner.kTranslator.mData.HOST_SearchTools_FindUnsupportedBlendMode_msg3, VECleaner.kTranslator.mData.HOST_SearchTools_FindUnsupportedBlendMode_msg4, VECleaner.kTranslator.mData.HOST_SearchTools_FindUnsupportedBlendMode_msg5]);
                    }
                    for (var i = 0; i < blendModeHandler_1.mAllComps.length; i++) {
                        var comp_3 = blendModeHandler_1.mAllComps[i];
                        comp_3.mUIIdx = [];
                        for (var g = 0; g < comp_3.mUnsupportedLayers.length; g++) {
                            var row = SearchTools.kBlendModeWindow.mList.add("item", comp_3.mComp.name);
                            row.subItems[0].text = comp_3.mUnsupportedLayers[g].index;
                            row.subItems[1].text = comp_3.mUnsupportedLayers[g].name;
                            comp_3.mUIIdx.push(row.index);
                        }
                    }
                    SearchTools.kBlendModeWindow.addShowButton(VECleaner.kTranslator.mData.HOST_SearchTools_FindUnsupportedBlendMode_msg6, function () {
                        if (SearchTools.kBlendModeWindow.mList.selection != null) {
                            CompCleaner.ClearSelection(blendModeHandler_1.mMainComp);
                            var sel = SearchTools.kBlendModeWindow.mList.selection.index;
                            blendModeHandler_1.selectAt(sel);
                        }
                    });
                    SearchTools.kBlendModeWindow.show();
                }
            }
            else {
                alert(VECleaner.kTranslator.mData.HOST_SearchTools_FindUnsupportedBlendMode_msg7);
                return false;
            }
            return true;
        };
        SearchTools.FindUnsupportedLayers = function () {
        };
        SearchTools.kBigVideoFileWindow = null;
        SearchTools.k3DLayerWindow = null;
        SearchTools.kBlendModeWindow = null;
        return SearchTools;
    }());
    var EditableGroupPanel = (function () {
        function EditableGroupPanel(holder, parent) {
            this.mParent = parent;
            this.mPanel = holder.add("panel", undefined, "");
            this.mPanel.alignment = ["fill", "bottom"];
            this.mPanel.orientation = "column";
            this.setLayerInfo(null);
        }
        EditableGroupPanel.prototype.setLayerInfo = function (info) {
            while (this.mPanel.children.length > 0) {
                this.mPanel.remove(0);
            }
            this.mLayerInfos = info;
            if (info == null) {
                this.mPanel.text = "";
                this.mPanel.alignChildren = ["fill", "fill"];
                var label = this.mPanel.add("statictext", undefined, VECleaner.kTranslator.mData.HOST_EditableGroupPanel_constructor_msg15);
            }
            else {
                var self_1 = this;
                this.mPanel.alignChildren = ["fill", "top"];
                this.mPanel.text = VECleaner.kTranslator.mData.HOST_EditableGroupPanel_constructor_msg1 + info[0].mGroup.toString();
                var topGr = this.mPanel.add("group");
                topGr.orientation = "row";
                this.mTimeLabel = topGr.add("statictext", undefined, VECleaner.kTranslator.mData.HOST_EditableGroupPanel_constructor_msg2);
                this.mTimeLabel.alignment = ["fill", "fill"];
                var timeInfo = this.mParent.getGroupTimeStamp(this.mLayerInfos[0].mGroup);
                if (timeInfo) {
                    this.mTimeLabel.text = VECleaner.kTranslator.mData.HOST_EditableGroupPanel_constructor_msg3 + timeInfo.mLayer.containingComp.name + VECleaner.kTranslator.mData.HOST_EditableGroupPanel_constructor_msg4 + timeInfo.mTimeStamp.toString() + "s";
                }
                this.mSetGroupTime = topGr.add("button", undefined, VECleaner.kTranslator.mData.HOST_EditableGroupPanel_constructor_msg5);
                this.mSetGroupTime.alignment = ["right", "fill"];
                this.mSetGroupTime.onClick = function () {
                    if (self_1.mParent.setGroupTimeStamp(self_1.mLayerInfos[0].mGroup)) {
                        self_1.updateTimeStampDisplay();
                    }
                };
                this.mLayerList = this.mPanel.add("listbox", undefined, undefined, { multiselect: true, numberOfColumns: 4, showHeaders: true, columnTitles: [VECleaner.kTranslator.mData.HOST_EditableGroupPanel_constructor_msg6, VECleaner.kTranslator.mData.HOST_EditableGroupPanel_constructor_msg7, VECleaner.kTranslator.mData.HOST_EditableGroupPanel_constructor_msg8, VECleaner.kTranslator.mData.HOST_EditableGroupPanel_constructor_msg9] });
                this.mLayerList.alignment = ["fill", "fill"];
                for (var i = 0; i < this.mLayerInfos.length; i++) {
                    var ll = this.mLayerInfos[i];
                    var row = this.mLayerList.add("item", ll.mLayer.containingComp.name);
                    row.subItems[0].text = ll.mLayer.index.toString();
                    row.subItems[1].text = ll.mLayer.name;
                    row.subItems[2].text = ll.mType == EditableType.kImageSource ? VECleaner.kTranslator.mData.HOST_EditableGroupPanel_constructor_msg10 : VECleaner.kTranslator.mData.HOST_EditableGroupPanel_constructor_msg11;
                }
                var bottomgr = this.mPanel.add("group");
                bottomgr.orientation = "row";
                bottomgr.alignChildren = ["fill", "fill"];
                this.mMoveUp = bottomgr.add("button", undefined, VECleaner.kTranslator.mData.HOST_EditableGroupPanel_constructor_msg12);
                this.mMoveUp.onClick = function () {
                    self_1.mParent.moveGroupUp(info[0].mGroup);
                };
                this.mMoveDown = bottomgr.add("button", undefined, VECleaner.kTranslator.mData.HOST_EditableGroupPanel_constructor_msg13);
                this.mMoveDown.onClick = function () {
                    self_1.mParent.moveGroupDown(info[0].mGroup);
                };
                this.mReleaseGroup = bottomgr.add("button", undefined, VECleaner.kTranslator.mData.HOST_EditableGroupPanel_constructor_msg14);
                this.mReleaseGroup.onClick = function () {
                    self_1.mParent.releaseGroup(info[0].mGroup);
                };
            }
        };
        EditableGroupPanel.prototype.updateTimeStampDisplay = function () {
            var info = this.mParent.getGroupTimeStamp(this.mLayerInfos[0].mGroup);
            if (info) {
                this.mTimeLabel.text = VECleaner.kTranslator.mData.HOST_EditableGroupPanel_updateTimeStampDisplay_msg1 + info.mLayer.containingComp.name + VECleaner.kTranslator.mData.HOST_EditableGroupPanel_updateTimeStampDisplay_msg2 + info.mTimeStamp.toString() + "s";
            }
            else {
                this.mTimeLabel.text = VECleaner.kTranslator.mData.HOST_EditableGroupPanel_updateTimeStampDisplay_msg3;
            }
            this.mParent.updateTimeStampDisplay(info);
            this.mParent.updateLayout();
        };
        EditableGroupPanel.prototype.panel = function () {
            return this.mPanel;
        };
        return EditableGroupPanel;
    }());
    var EditableLayerPanel = (function () {
        function EditableLayerPanel() {
            this.mInfo = null;
            this.mTimeStampInfo = null;
            var self = this;
            this.mPanel = new Window("palette", VECleaner.kTranslator.mData.HOST_EditableLayerPanel_constructor_msg1, undefined, { resizeable: true });
            this.mPanel.orientation = "column";
            this.mPanel.minimumSize.height = 400;
            this.mMainGroup = this.mPanel.add("group");
            this.mMainGroup.orientation = "row";
            this.mMainGroup.alignment = ["fill", "fill"];
            var leftGr = this.mMainGroup.add("panel", undefined, VECleaner.kTranslator.mData.HOST_EditableLayerPanel_constructor_msg2);
            leftGr.orientation = "column";
            leftGr.alignment = ["left", "fill"];
            this.mEditableLayerList = leftGr.add("listbox", undefined, undefined, { multiselect: true, numberOfColumns: 3, showHeaders: true, columnTitles: [VECleaner.kTranslator.mData.HOST_EditableLayerPanel_constructor_msg3, VECleaner.kTranslator.mData.HOST_EditableLayerPanel_constructor_msg4, VECleaner.kTranslator.mData.HOST_EditableLayerPanel_constructor_msg5] });
            this.mEditableLayerList.alignment = ["fill", "fill"];
            this.mEditableLayerList.preferredSize.width = 300;
            var leftBottomGr = leftGr.add("group");
            leftBottomGr.orientation = "row";
            leftBottomGr.alignment = ["fill", "bottom"];
            leftBottomGr.alignChildren = ["fill", "fill"];
            this.mCreateGroupBtn = leftBottomGr.add("button", undefined, VECleaner.kTranslator.mData.HOST_EditableLayerPanel_constructor_msg6);
            this.mCreateGroupBtn.onClick = function () {
                var indices = [];
                var items = self.mEditableLayerList.items;
                for (var i = 0; i < items.length; i++) {
                    if (items[i].selected) {
                        indices.push(i + 1);
                    }
                }
                if (indices.length > 0) {
                    self.mInfo.makeGroupFromLayers(indices);
                }
                self.updateContent();
            };
            this.mReviewSelectedLayer = leftBottomGr.add("button", undefined, VECleaner.kTranslator.mData.HOST_EditableLayerPanel_constructor_msg7);
            this.mReviewSelectedLayer.onClick = function () {
                var items = self.mEditableLayerList.items;
                for (var i = 0; i < items.length; i++) {
                    if (items[i].selected) {
                        CompCleaner.ClearSelection(self.mInfo.mOtherEditableLayer[i].mLayer.containingComp);
                        self.mInfo.mOtherEditableLayer[i].mLayer.containingComp.openInViewer();
                        self.mInfo.mOtherEditableLayer[i].mLayer.selected = true;
                        return;
                    }
                }
            };
            this.mGroupPanelHolder = this.mMainGroup.add("panel", undefined, VECleaner.kTranslator.mData.HOST_EditableLayerPanel_constructor_msg8);
            this.mGroupPanelHolder.alignment = ["fill", "fill"];
            this.mEditableGroupList = this.mGroupPanelHolder.add("listbox", undefined, undefined, { multiselect: false, numberOfColumns: 3, showHeaders: true, columnTitles: [VECleaner.kTranslator.mData.HOST_EditableLayerPanel_constructor_msg10, VECleaner.kTranslator.mData.HOST_EditableLayerPanel_constructor_msg11, VECleaner.kTranslator.mData.HOST_EditableLayerPanel_constructor_msg12] });
            this.mEditableGroupList.alignment = ["fill", "fill"];
            this.mEditableGroupList.onChange = function () {
                self.groupListSelectionChange();
            };
            this.mGroupDetailPanel = new EditableGroupPanel(this.mGroupPanelHolder, this);
            this.mExportGroupTimeStampBtn = this.mPanel.add("button", undefined, VECleaner.kTranslator.mData.HOST_EditableLayerPanel_constructor_msg9);
            this.mExportGroupTimeStampBtn.alignment = ["right", "bottom"];
            this.mExportGroupTimeStampBtn.onClick = function () {
                self.exportGroupTimeStampInfo();
            };
            self.updateContent();
        }
        EditableLayerPanel.prototype.groupListSelectionChange = function () {
            if (this.mEditableGroupList.selection == null) {
                this.mGroupDetailPanel.setLayerInfo(null);
            }
            else {
                var infos = this.mInfo.mGroupedEditableLayers[this.mEditableGroupList.selection.index];
                this.mGroupDetailPanel.setLayerInfo(infos);
            }
            this.updateLayout();
        };
        EditableLayerPanel.prototype.updateContent = function () {
            this.mInfo = new EditableLayerHandler();
            if (this.mTimeStampInfo == null) {
                this.mTimeStampInfo = GroupTimeStampHandler.GetDefaultTimeStampHandler();
            }
            this.mEditableLayerList.removeAll();
            for (var i = 0; i < this.mInfo.mOtherEditableLayer.length; i++) {
                var ll = this.mInfo.mOtherEditableLayer[i];
                var row = this.mEditableLayerList.add("item", ll.mLayer.containingComp.name);
                row.subItems[0].text = ll.mLayer.index.toString();
                row.subItems[1].text = ll.mLayer.name;
            }
            this.mEditableGroupList.removeAll();
            for (var i = 0; i < this.mInfo.mGroupedEditableLayers.length; i++) {
                var group = this.mInfo.mGroupedEditableLayers[i];
                var row = this.mEditableGroupList.add("item", (group[0].mGroup).toString());
                row.subItems[0].text = group.length.toString();
                var time = this.getGroupTimeStamp(group[0].mGroup);
                if (time != null) {
                    row.subItems[1].text = time.mTimeStamp.toString() + "s";
                }
                else {
                    row.subItems[1].text = VECleaner.kTranslator.mData.HOST_EditableGroupPanel_updateTimeStampDisplay_msg3;
                }
            }
            this.groupListSelectionChange();
            this.updateLayout();
        };
        EditableLayerPanel.prototype.updateLayout = function () {
            this.mPanel.layout.layout(true);
        };
        EditableLayerPanel.prototype.updateTimeStampDisplay = function (time) {
            if (this.mEditableGroupList.selection) {
                var selection = this.mEditableGroupList.selection.index;
                this.mEditableGroupList.items[selection].subItems[1].text = time == null ? VECleaner.kTranslator.mData.HOST_EditableGroupPanel_updateTimeStampDisplay_msg3 : time.mTimeStamp.toString() + "s";
            }
        };
        EditableLayerPanel.prototype.moveGroupUp = function (group) {
            if (this.mInfo.moveGroupUp(group)) {
                if (this.mTimeStampInfo) {
                    var c = this.mTimeStampInfo.getStampForGroup(group);
                    var u = this.mTimeStampInfo.getStampForGroup(group - 1);
                    if (c) {
                        c.setGroup(group - 1);
                        c.updateToLayer();
                    }
                    if (u) {
                        u.setGroup(group);
                        u.updateToLayer();
                    }
                }
                this.updateContent();
                this.updateLayout();
            }
        };
        EditableLayerPanel.prototype.moveGroupDown = function (group) {
            if (this.mInfo.moveGroupDown(group)) {
                if (this.mTimeStampInfo) {
                    var c = this.mTimeStampInfo.getStampForGroup(group);
                    var n = this.mTimeStampInfo.getStampForGroup(group + 1);
                    if (c) {
                        c.setGroup(group + 1);
                        c.updateToLayer();
                    }
                    if (n) {
                        n.setGroup(group);
                        n.updateToLayer();
                    }
                }
                this.updateContent();
                this.updateLayout();
            }
        };
        EditableLayerPanel.prototype.releaseGroup = function (group) {
            this.removeGroupTimeStamp(group);
            this.mInfo.releaseGroup(group);
            this.updateContent();
            this.updateLayout();
        };
        EditableLayerPanel.prototype.getGroupTimeStamp = function (group) {
            if (this.mTimeStampInfo) {
                return this.mTimeStampInfo.getStampForGroup(group);
            }
            return null;
        };
        EditableLayerPanel.prototype.removeGroupTimeStamp = function (group) {
            if (this.mTimeStampInfo) {
                this.mTimeStampInfo.removeStampForGroup(group);
            }
        };
        EditableLayerPanel.prototype.setGroupTimeStamp = function (group) {
            var comp = DomUtils.GetCurrentComp();
            if (comp == null) {
                if (this.mTimeStampInfo == null) {
                    alert(VECleaner.kTranslator.mData.HOST_EditableLayerPanel_setGroupTimeStamp_msg1);
                }
                else {
                    this.mTimeStampInfo.addStampForGroup(group);
                    return true;
                }
            }
            else {
                if (this.mTimeStampInfo == null) {
                    this.mTimeStampInfo = new GroupTimeStampHandler(comp);
                    this.mTimeStampInfo.addStampForGroup(group);
                    return true;
                }
                else {
                    if (this.mTimeStampInfo.mMainComp.id == comp.id) {
                        this.mTimeStampInfo.addStampForGroup(group);
                        return true;
                    }
                    else {
                        var ret = confirm(VECleaner.kTranslator.mData.HOST_EditableLayerPanel_setGroupTimeStamp_msg2, true, VECleaner.kTranslator.mData.HOST_EditableLayerPanel_setGroupTimeStamp_msg3);
                        if (ret) {
                            this.mTimeStampInfo.removeAll();
                            this.mTimeStampInfo = new GroupTimeStampHandler(comp);
                            this.mTimeStampInfo.addStampForGroup(group);
                            return true;
                        }
                    }
                }
            }
            return false;
        };
        EditableLayerPanel.prototype.exportGroupTimeStampInfo = function () {
            if (this.mTimeStampInfo) {
                var content = this.mTimeStampInfo.exportGroupTimeStampInfo();
                if (content.length > 0) {
                    var folder = Folder.selectDialog(VECleaner.kTranslator.mData.HOST_EditableLayerPanel_exportGroupTimeStampInfo_msg1);
                    if (folder) {
                        var filePath = folder.fsName + "/times.json";
                        var file = new File(filePath);
                        file.open("w");
                        file.encoding = "utf-8";
                        file.write(content);
                        file.close();
                        alert(VECleaner.kTranslator.mData.HOST_EditableLayerPanel_exportGroupTimeStampInfo_msg2);
                        return;
                    }
                    else {
                        return;
                    }
                }
            }
            alert(VECleaner.kTranslator.mData.HOST_EditableLayerPanel_exportGroupTimeStampInfo_msg3);
        };
        EditableLayerPanel.prototype.show = function () {
            var panel = this.mPanel;
            panel.layout.layout(true);
            panel.layout.resize();
            if (panel instanceof Window) {
                panel.onResizing = function () {
                    panel.layout.resize();
                };
            }
            if (panel && panel instanceof Window) {
                panel.show();
            }
        };
        EditableLayerPanel.prototype.close = function () {
            this.mPanel.close();
        };
        return EditableLayerPanel;
    }());
    var Vec2 = (function () {
        function Vec2(x, y) {
            this.mX = x;
            this.mY = y;
        }
        Vec2.prototype.max = function (other) {
            return new Vec2(Math.max(this.mX, other.mX), Math.max(this.mY, other.mY));
        };
        return Vec2;
    }());
    var Affine = (function () {
        function Affine() {
            this.mA = 1.0;
            this.mB = 0;
            this.mC = 0;
            this.mD = 1.0;
            this.mE = 0;
            this.mF = 0;
        }
        Affine.prototype.copy = function (other) {
            this.mA = other.mA;
            this.mB = other.mB;
            this.mC = other.mC;
            this.mD = other.mD;
            this.mE = other.mE;
            this.mF = other.mF;
        };
        Affine.prototype.set = function (anchor, position, scale, rotation) {
            rotation = rotation * 0.017453292519943;
            var cs = Math.cos(rotation), sn = Math.sin(rotation);
            this.mA = cs * scale.mX;
            this.mB = sn * scale.mX;
            this.mC = -sn * scale.mY;
            this.mD = cs * scale.mY;
            this.mE = position.mX;
            this.mF = position.mY;
            this.translate(-anchor.mX, -anchor.mY);
        };
        Affine.prototype.multiply = function (other) {
            var t0 = this.mA * other.mA + this.mB * other.mC;
            var t2 = this.mC * other.mA + this.mD * other.mC;
            var t4 = this.mE * other.mA + this.mF * other.mC + other.mE;
            this.mB = this.mA * other.mB + this.mB * other.mD;
            this.mD = this.mC * other.mB + this.mD * other.mD;
            this.mF = this.mE * other.mB + this.mF * other.mD + other.mF;
            this.mA = t0;
            this.mC = t2;
            this.mE = t4;
        };
        Affine.prototype.premultiply = function (other) {
            var s2 = new Affine();
            s2.copy(other);
            s2.multiply(this);
            this.copy(s2);
        };
        Affine.prototype.setTranslate = function (tx, ty) {
            this.mA = this.mD = 1.0;
            this.mB = this.mC = 0.0;
            this.mE = tx;
            this.mF = ty;
        };
        Affine.prototype.translate = function (tx, ty) {
            var t = new Affine();
            t.setTranslate(tx, ty);
            this.premultiply(t);
        };
        Affine.prototype.transform = function (point) {
            return new Vec2(this.mA * point.mX + this.mC * point.mY + this.mE, this.mB * point.mX + this.mD * point.mY + this.mF);
        };
        return Affine;
    }());
    var TextEditorDataVer1 = (function () {
        function TextEditorDataVer1(data) {
            this.mData = data;
        }
        TextEditorDataVer1.prototype.editSize = function () {
            return new Vec2(this.mData.area[2], this.mData.area[3]);
        };
        TextEditorDataVer1.prototype.getAnchor = function () {
            return new Vec2(0, 0);
        };
        TextEditorDataVer1.prototype.getPosition = function () {
            return new Vec2(this.mData.area[0], this.mData.area[1]);
        };
        TextEditorDataVer1.prototype.getScale = function () {
            return new Vec2(1, 1);
        };
        TextEditorDataVer1.prototype.getRotation = function () {
            return 0;
        };
        TextEditorDataVer1.prototype.getArea = function () {
            return this.mData.area;
        };
        return TextEditorDataVer1;
    }());
    var ImageEditorDataVer1 = (function () {
        function ImageEditorDataVer1(data, size) {
            this.mData = data;
            this.mSize = new Vec2(size.mX, size.mY);
        }
        ImageEditorDataVer1.prototype.editSize = function () {
            return this.mSize;
        };
        ImageEditorDataVer1.prototype.getArea = function () {
            var affine = new Affine();
            affine.set(this.getAnchor(), this.getPosition(), this.getScale(), this.getRotation());
            var tl = affine.transform(new Vec2(0, 0));
            var tr = affine.transform(new Vec2(this.mSize.mX, 0));
            var br = affine.transform(new Vec2(this.mSize.mX, this.mSize.mY));
            var bl = affine.transform(new Vec2(0, this.mSize.mY));
            var minX = Math.min(tl.mX, tr.mX, br.mX, bl.mX);
            var minY = Math.min(tl.mY, tr.mY, br.mY, bl.mY);
            var maxX = Math.max(tl.mX, tr.mX, br.mX, bl.mX);
            var maxY = Math.max(tl.mY, tr.mY, br.mY, bl.mY);
            return [minX, minY, maxX - minX, maxY - minY];
        };
        ImageEditorDataVer1.prototype.getAnchor = function () {
            return new Vec2(this.mData.a[0], this.mData.a[1]);
        };
        ImageEditorDataVer1.prototype.getPosition = function () {
            return new Vec2(this.mData.p[0], this.mData.p[1]);
        };
        ImageEditorDataVer1.prototype.getScale = function () {
            return new Vec2(this.mData.s[0], this.mData.s[1]);
        };
        ImageEditorDataVer1.prototype.getRotation = function () {
            return this.mData.r;
        };
        return ImageEditorDataVer1;
    }());
    var AssetDataVer1 = (function () {
        function AssetDataVer1(data) {
            this.mData = data;
            this.mGroup = null;
            this.mSize = new Vec2(data.size[0], data.size[1]);
            if (typeof (data.ui) != "undefined") {
                this.mGroup = data.ui.group;
                var type = data.ui.type;
                if (type == 2) {
                    this.mEditorData = new TextEditorDataVer1(data.ui);
                }
                else if (type == 1) {
                    this.mEditorData = new ImageEditorDataVer1(data.ui, this.mSize);
                }
            }
        }
        AssetDataVer1.prototype.convert = function () {
            if (this.mEditorData) {
                this.mEditorData.mData.area = this.mEditorData.getArea();
                var p = this.mEditorData.getPosition();
                var a = this.mEditorData.getAnchor();
                var s = this.mEditorData.getScale();
                var r = this.mEditorData.getRotation();
                var es = this.mEditorData.editSize();
                this.mEditorData.mData.a = [a.mX, a.mY];
                this.mEditorData.mData.p = [p.mX, p.mY];
                this.mEditorData.mData.s = [s.mX, s.mY];
                this.mEditorData.mData.r = r;
                this.mEditorData.mData.editSize = [es.mX, es.mY];
            }
        };
        AssetDataVer1.prototype.getData = function () {
            if (this.mEditorData == null) {
                return this.mData;
            }
            else {
                this.mData.ui = this.mEditorData.mData;
                return this.mData;
            }
        };
        return AssetDataVer1;
    }());
    var EditorGroupSizeInfo = (function () {
        function EditorGroupSizeInfo(index, size) {
            this.mIndex = index;
            this.mSize = new Vec2(size.mX, size.mY);
        }
        EditorGroupSizeInfo.prototype.updateSize = function (size) {
            this.mSize = this.mSize.max(size);
        };
        EditorGroupSizeInfo.prototype.getSize = function () {
            return { size: [this.mSize.mX, this.mSize.mY] };
        };
        return EditorGroupSizeInfo;
    }());
    var TemplateDataVer1ToVer2Convetor = (function () {
        function TemplateDataVer1ToVer2Convetor(folderPath, outputFolderPath) {
            this.mIsVer1 = false;
            this.mAssets = [];
            this.mGroupInfo = [];
            this.mTemplateFolder = new Folder(folderPath);
            this.mOutputFolderPath = outputFolderPath;
            var configFile = this.getFileInFolder("config.json");
            if (configFile) {
                this.mData = TemplateDataVer1ToVer2Convetor.ReadFileContent(configFile.fsName);
                if (this.mData != null) {
                    if (typeof (this.mData.ui_version) == "undefined" || parseInt(this.mData.ui_version.charAt(0)) < 2) {
                        this.mIsVer1 = true;
                    }
                }
                if (this.mIsVer1) {
                    var assets = this.mData.assets;
                    for (var i = 0; i < assets.length; i++) {
                        var data = new AssetDataVer1(assets[i]);
                        if (data.mEditorData != null) {
                            this.updateGroupSizes(data);
                        }
                        data.convert();
                        this.mAssets.push(data);
                    }
                    this.reorderGroups();
                    this.mData.assets = [];
                    for (var i = 0; i < this.mAssets.length; i++) {
                        this.mData.assets.push(this.mAssets[i].getData());
                    }
                    this.mData.ui_version = "2.0";
                    this.mData.ui_group = [];
                    for (var i = 0; i < this.mGroupInfo.length; i++) {
                        this.mData.ui_group.push(this.mGroupInfo[i].getSize());
                    }
                    var mainCompName = this.mData.main;
                    var size = [0, 0];
                    var duration = 0;
                    var comps = this.mData.comps;
                    for (var i = 0; i < comps.length; i++) {
                        var comp = comps[i];
                        if (comp.name == mainCompName) {
                            size = comp.size;
                            duration = comp.duration;
                        }
                    }
                    this.mData.size = size;
                    this.mData.duration = duration;
                }
            }
        }
        TemplateDataVer1ToVer2Convetor.prototype["export"] = function () {
            var content = TemplateUIDataUtils.ReorderConfigAssetsGroupByInpoint(this.mData);
            this.writeJsonFile(content, "config.json", "");
            this.copyFolder("assets");
            this.copyFolder("ui");
            this.copyFolder("datas");
            this.copyMusic();
        };
        TemplateDataVer1ToVer2Convetor.prototype.updateGroupSizes = function (asset) {
            if (typeof (asset.mGroup) == "number") {
                var group = null;
                for (var i = 0; i < this.mGroupInfo.length; i++) {
                    if (this.mGroupInfo[i].mIndex == asset.mGroup) {
                        group = this.mGroupInfo[i];
                        break;
                    }
                }
                if (group == null) {
                    group = new EditorGroupSizeInfo(asset.mGroup, asset.mSize);
                    this.mGroupInfo.push(group);
                }
                group.updateSize(asset.mSize);
            }
        };
        TemplateDataVer1ToVer2Convetor.prototype.reorderGroups = function () {
            this.mGroupInfo.sort(function (a, b) {
                return a.mIndex - b.mIndex;
            });
        };
        TemplateDataVer1ToVer2Convetor.prototype.getFileInFolder = function (name) {
            var path = this.mTemplateFolder.fsName + "/" + name;
            var file = new File(path);
            if (file.exists) {
                return file;
            }
            return null;
        };
        TemplateDataVer1ToVer2Convetor.prototype.writeJsonFile = function (data, name, folder) {
            var folderPath = folder && folder.length > 0 ? (this.mOutputFolderPath + "/" + folder) : this.mOutputFolderPath;
            var folderObj = new Folder(folderPath);
            if (!folderObj.exists) {
                folderObj.create();
            }
            var path = folderPath + "/" + name;
            var file = new File(path);
            file.open("w");
            file.encoding = "utf-8";
            file.write(data);
            file.close();
        };
        TemplateDataVer1ToVer2Convetor.prototype.copyFile = function (name, newName, folder) {
            var folderPath = folder && folder.length > 0 ? (this.mOutputFolderPath + "/" + folder) : this.mOutputFolderPath;
            var folderObj = new Folder(folderPath);
            if (!folderObj.exists) {
                folderObj.create();
            }
            var path = folderPath + "/" + newName;
            var file = new File(this.mTemplateFolder.fsName + "/" + name);
            if (file.exists) {
                file.copy(path);
            }
        };
        TemplateDataVer1ToVer2Convetor.prototype.copyMusic = function () {
            var musicName = "/music.mp3";
            var musicPath = this.mTemplateFolder.fsName + musicName;
            var musicFile = new File(musicPath);
            if (!musicFile.exists) {
                musicName = "/music.aac";
                musicPath = this.mTemplateFolder.fsName + musicName;
                musicFile = new File(musicPath);
            }
            if (musicFile.exists) {
                musicFile.copy(this.mOutputFolderPath + musicName);
            }
        };
        TemplateDataVer1ToVer2Convetor.prototype.copyFolder = function (folder) {
            var oldFolder = new Folder(this.mTemplateFolder.fsName + "/" + folder);
            if (oldFolder.exists) {
                var folderPath = folder && folder.length > 0 ? (this.mOutputFolderPath + "/" + folder) : this.mOutputFolderPath;
                var folderObj = new Folder(folderPath);
                if (!folderObj.exists) {
                    folderObj.create();
                }
                var files = oldFolder.getFiles("");
                for (var f = 0; f < files.length; f++) {
                    var file = files[f];
                    if (file instanceof File) {
                        file.copy(this.mOutputFolderPath + "/" + folder + "/" + file.displayName);
                    }
                }
            }
        };
        TemplateDataVer1ToVer2Convetor.ReadFileContent = function (filePath) {
            var file = new File(filePath);
            if (file.exists) {
                file.open("r");
                file.encoding = "utf-8";
                var content = file.read(999999999);
                file.close();
                var data = null;
                try {
                    data = JSON.parse(content);
                }
                catch (error) {
                    data = null;
                }
                return data;
            }
            return null;
        };
        return TemplateDataVer1ToVer2Convetor;
    }());
    var Logger = (function () {
        function Logger(folder) {
            var folderObj = new Folder(folder);
            if (!folderObj.exists) {
                folderObj.create();
            }
            var path = folder + "/log.txt";
            this.mLogFile = new File(path);
        }
        Logger.prototype.writeLogContent = function (content) {
            var date = new Date();
            content = "[" + date.toLocaleDateString() + "-" + date.toLocaleTimeString() + "]:" + content;
            this.mLogFile.writeln(content);
            this.mLogFile.close();
            this.mLogFile.open("a");
        };
        Logger.prototype.close = function () {
            this.mLogFile.close();
        };
        return Logger;
    }());
    var NormalTemplateVersionConvertorWindow = (function () {
        function NormalTemplateVersionConvertorWindow() {
            this.mSingleInputTemplateFolder = "";
            this.mSingleOutputTemplateFolder = "";
            this.mMultipleInputTemplateFolder = "";
            this.mMultipleOutputTemplateFolder = "";
            var self = this;
            this.mPanel = new Window("palette", VECleaner.kTranslator.mData.HOST_TemplateConvertionTools_NormalTemplateVersionConvertorWindow_msg1, undefined, { resizeable: true });
            this.mPanel.orientation = "row";
            this.mMainTab = this.mPanel.add("tabbedpanel");
            this.mMainTab.alignment = ["fill", "fill"];
            this.mSingleTemplateConvertPanel = this.mMainTab.add("tab", undefined, VECleaner.kTranslator.mData.HOST_TemplateConvertionTools_NormalTemplateVersionConvertorWindow_msg2);
            this.mSingleTemplateConvertPanel.orientation = "column";
            this.mMultipleTemplatesConvertPanel = this.mMainTab.add("tab", undefined, VECleaner.kTranslator.mData.HOST_TemplateConvertionTools_NormalTemplateVersionConvertorWindow_msg3);
            var title1 = this.mSingleTemplateConvertPanel.add("statictext", undefined, VECleaner.kTranslator.mData.HOST_TemplateConvertionTools_NormalTemplateVersionConvertorWindow_msg4);
            title1.alignment = ["center", "top"];
            var topGr1 = this.mSingleTemplateConvertPanel.add("group");
            topGr1.alignment = ["fill", "top"];
            var inputLabel1 = topGr1.add("statictext", undefined, VECleaner.kTranslator.mData.HOST_TemplateConvertionTools_NormalTemplateVersionConvertorWindow_msg5);
            inputLabel1.alignment = ["left", "center"];
            var inputPath1 = topGr1.add("statictext", undefined, "");
            inputPath1.alignment = ["fill", "center"];
            var selectInputButton1 = topGr1.add("button", undefined, "...");
            selectInputButton1.alignment = ["right", "center"];
            selectInputButton1.onClick = function () {
                var folder = Folder.selectDialog(VECleaner.kTranslator.mData.HOST_TemplateConvertionTools_NormalTemplateVersionConvertorWindow_msg6);
                if (folder) {
                    self.mSingleInputTemplateFolder = folder.fsName;
                    inputPath1.text = self.mSingleInputTemplateFolder;
                }
            };
            var bottomGr1 = this.mSingleTemplateConvertPanel.add("group");
            bottomGr1.alignment = ["fill", "top"];
            var outputLabel1 = bottomGr1.add("statictext", undefined, VECleaner.kTranslator.mData.HOST_TemplateConvertionTools_NormalTemplateVersionConvertorWindow_msg7);
            outputLabel1.alignment = ["left", "center"];
            var outputPath1 = bottomGr1.add("statictext", undefined, "");
            outputPath1.alignment = ["fill", "center"];
            var selectOutputButton1 = bottomGr1.add("button", undefined, "...");
            selectOutputButton1.alignment = ["right", "center"];
            selectOutputButton1.onClick = function () {
                var folder = Folder.selectDialog(VECleaner.kTranslator.mData.HOST_TemplateConvertionTools_NormalTemplateVersionConvertorWindow_msg8);
                if (folder) {
                    self.mSingleOutputTemplateFolder = folder.fsName;
                    outputPath1.text = self.mSingleOutputTemplateFolder;
                }
            };
            this.mCreateTemplateFolder = this.mSingleTemplateConvertPanel.add("checkbox", undefined, VECleaner.kTranslator.mData.HOST_TemplateConvertionTools_NormalTemplateVersionConvertorWindow_msg9);
            this.mCreateTemplateFolder.value = true;
            this.mCreateTemplateFolder.alignment = ["left", "top"];
            var convertBtn1 = this.mSingleTemplateConvertPanel.add("button", undefined, VECleaner.kTranslator.mData.HOST_TemplateConvertionTools_NormalTemplateVersionConvertorWindow_msg10);
            convertBtn1.alignment = ["fill", "bottom"];
            convertBtn1.onClick = function () {
                self.convertSingleTemplate();
            };
            var title2 = this.mMultipleTemplatesConvertPanel.add("statictext", undefined, VECleaner.kTranslator.mData.HOST_TemplateConvertionTools_NormalTemplateVersionConvertorWindow_msg11);
            title2.alignment = ["center", "top"];
            var topGr2 = this.mMultipleTemplatesConvertPanel.add("group");
            topGr2.alignment = ["fill", "top"];
            var inputLabel2 = topGr2.add("statictext", undefined, VECleaner.kTranslator.mData.HOST_TemplateConvertionTools_NormalTemplateVersionConvertorWindow_msg5);
            inputLabel2.alignment = ["left", "center"];
            var inputPath2 = topGr2.add("statictext", undefined, "");
            inputPath2.alignment = ["fill", "center"];
            var selectInputButton2 = topGr2.add("button", undefined, "...");
            selectInputButton2.alignment = ["right", "center"];
            selectInputButton2.onClick = function () {
                var folder = Folder.selectDialog(VECleaner.kTranslator.mData.HOST_TemplateConvertionTools_NormalTemplateVersionConvertorWindow_msg6);
                if (folder) {
                    self.mMultipleInputTemplateFolder = folder.fsName;
                    inputPath2.text = self.mMultipleInputTemplateFolder;
                }
            };
            var bottomGr2 = this.mMultipleTemplatesConvertPanel.add("group");
            bottomGr2.alignment = ["fill", "top"];
            var outputLabel2 = bottomGr2.add("statictext", undefined, VECleaner.kTranslator.mData.HOST_TemplateConvertionTools_NormalTemplateVersionConvertorWindow_msg7);
            outputLabel2.alignment = ["left", "center"];
            var outputPath2 = bottomGr2.add("statictext", undefined, "");
            outputPath2.alignment = ["fill", "center"];
            var selectOutputButton2 = bottomGr2.add("button", undefined, "...");
            selectOutputButton2.alignment = ["right", "center"];
            selectOutputButton2.onClick = function () {
                var folder = Folder.selectDialog(VECleaner.kTranslator.mData.HOST_TemplateConvertionTools_NormalTemplateVersionConvertorWindow_msg8);
                if (folder) {
                    self.mMultipleOutputTemplateFolder = folder.fsName;
                    outputPath2.text = self.mMultipleOutputTemplateFolder;
                }
            };
            var convertBtn2 = this.mMultipleTemplatesConvertPanel.add("button", undefined, VECleaner.kTranslator.mData.HOST_TemplateConvertionTools_NormalTemplateVersionConvertorWindow_msg12);
            convertBtn2.alignment = ["fill", "bottom"];
            convertBtn2.onClick = function () {
                self.convertMultipleTemplates();
            };
        }
        NormalTemplateVersionConvertorWindow.prototype.convertSingleTemplate = function () {
            if (this.mSingleInputTemplateFolder.length == 0) {
                alert(VECleaner.kTranslator.mData.HOST_TemplateConvertionTools_NormalTemplateVersionConvertorWindow_msg13);
                return;
            }
            if (this.mSingleOutputTemplateFolder.length == 0) {
                alert(VECleaner.kTranslator.mData.HOST_TemplateConvertionTools_NormalTemplateVersionConvertorWindow_msg14);
                return;
            }
            var templateFolder = new Folder(this.mSingleInputTemplateFolder);
            if (templateFolder.exists) {
                var template = new TemplateDataVer1ToVer2Convetor(this.mSingleInputTemplateFolder, this.mCreateTemplateFolder.value ? this.mSingleOutputTemplateFolder + "/" + templateFolder.displayName : this.mSingleOutputTemplateFolder);
                if (!template.mIsVer1) {
                    alert(VECleaner.kTranslator.mData.HOST_TemplateConvertionTools_NormalTemplateVersionConvertorWindow_msg15);
                }
                else {
                    template["export"]();
                    alert(VECleaner.kTranslator.mData.HOST_TemplateConvertionTools_NormalTemplateVersionConvertorWindow_msg16);
                }
            }
            else {
                alert(VECleaner.kTranslator.mData.HOST_TemplateConvertionTools_NormalTemplateVersionConvertorWindow_msg13);
            }
        };
        NormalTemplateVersionConvertorWindow.prototype.convertMultipleTemplates = function () {
            var inputFolder = new Folder(this.mMultipleInputTemplateFolder);
            if (!(inputFolder.exists)) {
                alert(VECleaner.kTranslator.mData.HOST_TemplateConvertionTools_NormalTemplateVersionConvertorWindow_msg13);
                return;
            }
            var outputFolder = new Folder(this.mMultipleOutputTemplateFolder);
            if (!(outputFolder.exists)) {
                alert(VECleaner.kTranslator.mData.HOST_TemplateConvertionTools_NormalTemplateVersionConvertorWindow_msg14);
                return;
            }
            var logger = new Logger(this.mMultipleOutputTemplateFolder);
            var allFiles = inputFolder.getFiles(null);
            var subFolders = [];
            for (var i = 0; i < allFiles.length; i++) {
                if (allFiles[i] instanceof Folder) {
                    subFolders.push(allFiles[i]);
                }
            }
            var failCount = 0;
            for (var i = 0; i < subFolders.length; i++) {
                var templateFolder = subFolders[i];
                var template = new TemplateDataVer1ToVer2Convetor(templateFolder.fsName, this.mMultipleOutputTemplateFolder + "/" + templateFolder.displayName);
                if (!template.mIsVer1) {
                    logger.writeLogContent(VECleaner.kTranslator.format(VECleaner.kTranslator.mData.HOST_TemplateConvertionTools_NormalTemplateVersionConvertorWindow_msg17, templateFolder.fsName));
                    failCount++;
                }
                else {
                    template["export"]();
                    logger.writeLogContent(VECleaner.kTranslator.format(VECleaner.kTranslator.mData.HOST_TemplateConvertionTools_NormalTemplateVersionConvertorWindow_msg18, templateFolder.fsName));
                }
            }
            if (failCount > 0) {
                alert(VECleaner.kTranslator.format(VECleaner.kTranslator.mData.HOST_TemplateConvertionTools_NormalTemplateVersionConvertorWindow_msg19, failCount.toString()));
            }
            else {
                alert(VECleaner.kTranslator.mData.HOST_TemplateConvertionTools_NormalTemplateVersionConvertorWindow_msg16);
            }
        };
        NormalTemplateVersionConvertorWindow.prototype.update = function () {
            this.mPanel.layout.layout(true);
        };
        NormalTemplateVersionConvertorWindow.prototype.show = function () {
            var panel = this.mPanel;
            panel.layout.layout(true);
            panel.layout.resize();
            panel.onResizing = panel.onResize = function () {
                panel.layout.resize();
            };
            if (panel && panel instanceof Window) {
                panel.show();
            }
        };
        NormalTemplateVersionConvertorWindow.prototype.close = function () {
            if (this.mPanel) {
                this.mPanel.close();
            }
        };
        return NormalTemplateVersionConvertorWindow;
    }());
    var SelectLUTPanel = (function () {
        function SelectLUTPanel() {
            var self = this;
            this.mWin = new Window("dialog", "Select LUT File", undefined, { resizeable: true });
            this.mWin.orientation = "column";
            this.mWin.minimumSize[0] = 400;
            var outputGr = this.mWin.add("panel", undefined, "LUT Image File");
            outputGr.orientation = "row";
            outputGr.alignment = ["fill", "top"];
            var outputLabel = outputGr.add("statictext", undefined, "LUT File:");
            outputLabel.alignment = ["left", "center"];
            this.mLUTPath = outputGr.add("edittext", undefined, "", { readonly: true });
            this.mLUTPath.alignment = ["fill", "center"];
            this.mSelectLUT = outputGr.add("button", undefined, "...");
            this.mSelectLUT.alignment = ["right", "center"];
            this.mSelectLUT.onClick = function () {
                self.selectPNGFile();
            };
            var nameGr = this.mWin.add("panel", undefined, "Filter Name");
            nameGr.orientation = "row";
            nameGr.alignment = ["fill", "fill"];
            var nameLabel = nameGr.add("statictext", undefined, "Name:");
            nameLabel.alignment = ["left", "center"];
            this.mName = nameGr.add("edittext", undefined, "");
            this.mName.alignment = ["fill", "center"];
            var actionGr = this.mWin.add("group");
            actionGr.orientation = "row";
            actionGr.alignment = ["fill", "top"];
            this.mConvert = actionGr.add("button", undefined, "Convert to Template");
            this.mConvert.alignment = ["fill", "top"];
            this.mConvert.onClick = function () {
                if (self.mLUTPath.text.length == 0) {
                    alert("Please select a 512x512 LUT PNG image file!");
                }
                else {
                    self.mAction = "OK";
                    self.close();
                }
            };
            this.mCreate = actionGr.add("button", undefined, "Create Filter Comp");
            this.mCreate.alignment = ["fill", "top"];
            this.mCreate.onClick = function () {
                if (self.mLUTPath.text.length == 0) {
                    alert("Please select a 512x512 LUT PNG image file!");
                }
                else {
                    self.mAction = "Create";
                    self.close();
                }
            };
        }
        SelectLUTPanel.prototype.validateLUT = function () {
            if (this.mLUTPath.text.length > 0) {
                var f = ScriptUI.newImage(this.mLUTPath.text);
                if (f && f.size[0] == f.size[1] && f.size[1] == 512) {
                    return true;
                }
            }
            return false;
        };
        SelectLUTPanel.prototype.selectPNGFile = function () {
            var f = File.openDialog("LUT PNG file", "PNG file:*.png");
            if (f && f.exists) {
                this.mLUTPath.text = f.fsName;
                if (!this.validateLUT()) {
                    this.mLUTPath.text = "";
                    alert("Please select a 512x512 LUT PNG image file!");
                }
                else {
                    var dotIdx = f.displayName.lastIndexOf(".");
                    this.mName.text = f.displayName.substr(0, dotIdx);
                }
            }
            else {
                this.mLUTPath.text = "";
            }
        };
        SelectLUTPanel.prototype.update = function () {
            this.mWin.layout.layout(true);
        };
        SelectLUTPanel.prototype.show = function () {
            this.mAction = "Cancel";
            var panel = this.mWin;
            panel.onResizing = panel.onResize = function () {
                panel.layout.resize();
            };
            panel.layout.layout(true);
            panel.layout.resize();
            panel.show();
        };
        SelectLUTPanel.prototype.close = function () {
            if (this.mWin) {
                this.mWin.close();
            }
        };
        SelectLUTPanel.prototype.lutPath = function () {
            return this.mLUTPath.text.replace(/\\/g, "\/");
        };
        return SelectLUTPanel;
    }());
    var AssetConfigReader = (function () {
        function AssetConfigReader(data) {
            this.mData = data;
            this.mComp = null;
            this.mInpoint = 1000000.0;
        }
        AssetConfigReader.prototype.type = function () {
            return this.mData.type;
        };
        AssetConfigReader.prototype.key = function () {
            return this.mData.key;
        };
        AssetConfigReader.prototype.name = function () {
            return this.mData.name;
        };
        AssetConfigReader.prototype.group = function () {
            if (this.mData.ui) {
                return this.mData.ui.group;
            }
            return 0;
        };
        AssetConfigReader.prototype.setGroup = function (group) {
            if (this.mData.ui && group > 0) {
                this.mData.ui.group = group;
            }
        };
        AssetConfigReader.prototype.setInpoint = function (inpoint) {
            if (inpoint < this.mInpoint) {
                this.mInpoint = inpoint;
                this.mData.inpoint = this.mInpoint;
            }
        };
        return AssetConfigReader;
    }());
    var LayerConfigReader = (function () {
        function LayerConfigReader(data) {
            this.mData = data;
            this.mAsset = null;
            this.mGlobalInpoint = 100000;
        }
        LayerConfigReader.prototype.source = function () {
            return this.mData.source;
        };
        LayerConfigReader.prototype.globalInpoint = function () {
            return this.mGlobalInpoint;
        };
        LayerConfigReader.prototype.setGlobalInpoint = function (inpoint) {
            if (inpoint < this.mGlobalInpoint) {
                this.mGlobalInpoint = inpoint;
                if (this.mAsset) {
                    this.mAsset.setInpoint(this.mGlobalInpoint);
                    if (this.mAsset.mComp != null) {
                        this.mAsset.mComp.updateLayerAssetInpoint(this);
                    }
                }
            }
        };
        LayerConfigReader.prototype.inpoint = function () {
            return Math.max(0, this.mData.range[1] / this.mData.range[3]);
        };
        LayerConfigReader.prototype.startTime = function () {
            return Math.max(0, this.mData.range[0] / this.mData.range[3]);
        };
        LayerConfigReader.prototype.duration = function () {
            return Math.max(0, this.mData.range[2] / this.mData.range[3]);
        };
        LayerConfigReader.prototype.stretch = function () {
            if (typeof this.mData.stretch != "undefined") {
                return this.mData.stretch;
            }
            return 1.0;
        };
        return LayerConfigReader;
    }());
    var CompConfigReader = (function () {
        function CompConfigReader(template, data) {
            this.mData = data;
            this.mLayers = [];
            var layers = this.mData.layers;
            for (var l = 0; l < layers.length; l++) {
                var layer = new LayerConfigReader(layers[l]);
                layer.mAsset = template.getAsset(layer.source());
                this.mLayers.push(layer);
            }
        }
        CompConfigReader.prototype.name = function () {
            return this.mData.name;
        };
        CompConfigReader.prototype.layersWithSource = function (source) {
            var layers = [];
            for (var l = 0; l < this.mLayers.length; l++) {
                var layer = this.mLayers[l];
                if (layer.source() == source) {
                    layers.push(layer);
                }
            }
            return layers;
        };
        CompConfigReader.prototype.updateLayerAssetInpoint = function (containerLayer) {
            for (var l = 0; l < this.mLayers.length; l++) {
                var layer = this.mLayers[l];
                var inPoint = layer.inpoint();
                var duration = layer.duration();
                var endPoint = inPoint + duration;
                if (containerLayer) {
                    inPoint = inPoint * containerLayer.stretch();
                    duration = duration * containerLayer.stretch();
                    endPoint = endPoint * containerLayer.stretch();
                    var compInPoint = containerLayer.inpoint();
                    var compStartPoint = containerLayer.startTime();
                    var compEndPoint = compInPoint + containerLayer.duration();
                    if (endPoint <= (compInPoint - compStartPoint)) {
                        duration = 0;
                    }
                    else if (inPoint >= compEndPoint) {
                        duration = 0;
                    }
                    if (compInPoint > compStartPoint) {
                        if (inPoint < (compInPoint - compStartPoint)) {
                            inPoint = containerLayer.mGlobalInpoint;
                        }
                        else {
                            inPoint = inPoint + containerLayer.mGlobalInpoint - compInPoint + compStartPoint;
                        }
                    }
                    else
                        inPoint = inPoint + containerLayer.mGlobalInpoint;
                }
                if (duration > 0.001) {
                    layer.setGlobalInpoint(inPoint);
                }
            }
        };
        return CompConfigReader;
    }());
    var EditorGroupConfigReader = (function () {
        function EditorGroupConfigReader(asset) {
            this.mGroup = asset.group();
            this.mAssets = [asset];
            this.mInpoint = asset.mInpoint;
            this.mGroupData = null;
        }
        EditorGroupConfigReader.prototype.setGroup = function (group) {
            this.mGroup = group;
            for (var a = 0; a < this.mAssets.length; a++) {
                this.mAssets[a].setGroup(group);
            }
        };
        EditorGroupConfigReader.prototype.addAsset = function (asset) {
            for (var a = 0; a < this.mAssets.length; a++) {
                if (this.mAssets[a] == asset) {
                    return;
                }
            }
            this.mAssets.push(asset);
            if (asset.mInpoint < this.mInpoint) {
                this.mInpoint = asset.mInpoint;
            }
        };
        return EditorGroupConfigReader;
    }());
    var TemplateConfigReader = (function () {
        function TemplateConfigReader(data) {
            this.mData = data;
            this.mAssets = [];
            this.mComps = [];
            this.mGroups = [];
            var assets = this.mData.assets;
            for (var l = 0; l < assets.length; l++) {
                var asset = new AssetConfigReader(assets[l]);
                this.mAssets.push(asset);
            }
            var comps = this.mData.comps;
            for (var l = 0; l < comps.length; l++) {
                var comp = new CompConfigReader(this, comps[l]);
                this.mComps.push(comp);
                if (comp.name() == this.mData.main) {
                    this.mMainComp = comp;
                }
            }
            for (var l = 0; l < this.mAssets.length; l++) {
                var asset = this.mAssets[l];
                if (asset.type() == 3) {
                    asset.mComp = this.getComp(asset.name());
                }
            }
            this.mMainComp.updateLayerAssetInpoint(null);
            for (var l = 0; l < this.mAssets.length; l++) {
                var asset = this.mAssets[l];
                var group = this.getGroup(asset);
                group.addAsset(asset);
            }
        }
        TemplateConfigReader.prototype.getAsset = function (key) {
            for (var l = 0; l < this.mAssets.length; l++) {
                var asset = this.mAssets[l];
                if (asset.key() == key) {
                    return asset;
                }
            }
            return null;
        };
        TemplateConfigReader.prototype.getComp = function (name) {
            for (var l = 0; l < this.mComps.length; l++) {
                if (this.mComps[l].name() == name) {
                    return this.mComps[l];
                }
            }
            return null;
        };
        TemplateConfigReader.prototype.getGroup = function (asset) {
            for (var g_1 = 0; g_1 < this.mGroups.length; g_1++) {
                if (this.mGroups[g_1].mGroup == asset.group()) {
                    return this.mGroups[g_1];
                }
            }
            var g = new EditorGroupConfigReader(asset);
            if (g.mGroup > 0) {
                var groupDatas = this.mData.ui_group;
                g.mGroupData = groupDatas[g.mGroup - 1];
            }
            this.mGroups.push(g);
            return g;
        };
        TemplateConfigReader.prototype.reorderAssetGroupByIndex = function () {
            this.mGroups.sort(function (a, b) {
                return a.mGroup - b.mGroup;
            });
        };
        TemplateConfigReader.prototype.reorderAssetGroupByInpoint = function () {
            this.mGroups.sort(function (a, b) {
                return a.mInpoint - b.mInpoint;
            });
            this.mData.ui_group = [];
            var groupIndex = 1;
            for (var g = 0; g < this.mGroups.length; g++) {
                var group = this.mGroups[g];
                if (group.mGroup > 0) {
                    group.setGroup(groupIndex);
                    groupIndex++;
                    this.mData.ui_group.push(group.mGroupData);
                }
            }
        };
        TemplateConfigReader.prototype.updateAssetsOrderByGroupOrder = function () {
            this.mData.assets = [];
            for (var g = 0; g < this.mGroups.length; g++) {
                var group = this.mGroups[g];
                for (var a = 0; a < group.mAssets.length; a++) {
                    this.mData.assets.push(group.mAssets[a].mData);
                }
            }
        };
        return TemplateConfigReader;
    }());
    var TemplateUIDataUtils = (function () {
        function TemplateUIDataUtils() {
        }
        TemplateUIDataUtils.ReorderConfigAssetsGroupByInpoint = function (configData) {
            var templateConfig = new TemplateConfigReader(configData);
            templateConfig.reorderAssetGroupByInpoint();
            templateConfig.updateAssetsOrderByGroupOrder();
            return JSON.stringify(configData);
        };
        TemplateUIDataUtils.ReorderTemplateGroupByInpoint = function () {
            var f = File.openDialog("select config.json");
            var configPath = f.fsName;
            var configData = TemplateDataVer1ToVer2Convetor.ReadFileContent(configPath);
            var newContent = TemplateUIDataUtils.ReorderConfigAssetsGroupByInpoint(configData);
            TemplateUIDataUtils.WriteFileContent(configPath, newContent);
            alert("finish");
            return true;
        };
        TemplateUIDataUtils.FixNormalTemplate2InfoLost = function () {
            var f = File.openDialog("select config.json");
            var configPath = f.fsName;
            var configData = TemplateDataVer1ToVer2Convetor.ReadFileContent(configPath);
            var isVer2 = false;
            if (configData != null) {
                if (typeof (configData.ui_version) != "undefined" || parseInt(configData.ui_version.charAt(0)) == 2) {
                    isVer2 = true;
                }
            }
            if (isVer2) {
                var mainCompName = configData.main;
                var size = [0, 0];
                var duration = 0;
                var comps = configData.comps;
                for (var i = 0; i < comps.length; i++) {
                    var comp = comps[i];
                    if (comp.name == mainCompName) {
                        size = comp.size;
                        duration = comp.duration;
                    }
                }
                configData.size = size;
                configData.duration = duration;
                var newContent = TemplateUIDataUtils.ReorderConfigAssetsGroupByInpoint(configData);
                TemplateUIDataUtils.WriteFileContent(configPath, newContent);
                alert("finish");
            }
            else {
                alert("Please select a Normal Template 2.0 config.json file!");
            }
            return true;
        };
        TemplateUIDataUtils.WriteFileContent = function (filePath, content) {
            var configFile = new File(filePath);
            configFile.open("w");
            configFile.encoding = "utf-8";
            configFile.write(content);
            configFile.close();
        };
        return TemplateUIDataUtils;
    }());
    var TemplateConvertionTools = (function () {
        function TemplateConvertionTools() {
        }
        TemplateConvertionTools.ConvertVer1TemplateToVer2Template = function () {
            if (TemplateConvertionTools.kVersionConvertWindow) {
                TemplateConvertionTools.kVersionConvertWindow.close();
                TemplateConvertionTools.kVersionConvertWindow = null;
            }
            TemplateConvertionTools.kVersionConvertWindow = new NormalTemplateVersionConvertorWindow();
            TemplateConvertionTools.kVersionConvertWindow.show();
            return true;
        };
        TemplateConvertionTools.ConvertLUTImage2EditFilter = function () {
            if (TemplateConvertionTools.kLUTSelectWindow) {
                TemplateConvertionTools.kLUTSelectWindow.close();
                TemplateConvertionTools.kLUTSelectWindow = null;
            }
            TemplateConvertionTools.kLUTSelectWindow = new SelectLUTPanel();
            TemplateConvertionTools.kLUTSelectWindow.show();
            if (TemplateConvertionTools.kLUTSelectWindow.mAction == "OK") {
                var defaultConfig = JSON.parse(TemplateConvertionTools.kEditFilterConfig);
                if (TemplateConvertionTools.kLUTSelectWindow.mName.text.length > 0) {
                    defaultConfig.description = TemplateConvertionTools.kLUTSelectWindow.mName.text;
                }
                var outputFolder = Folder.selectDialog("Select an EMPTY folder to save your filter");
                if (outputFolder.exists) {
                    var assets = new Folder(outputFolder.fsName + "/assets");
                    assets.create();
                    var lutFile = new File(TemplateConvertionTools.kLUTSelectWindow.lutPath());
                    lutFile.copy(outputFolder.fsName + "/assets/asset2.png");
                    var configFile = new File(outputFolder.fsName + "/config.json");
                    configFile.open("w");
                    configFile.encoding = "utf-8";
                    configFile.write(JSON.stringify(defaultConfig));
                    configFile.close();
                    alert("DONE!");
                }
            }
            else if (TemplateConvertionTools.kLUTSelectWindow.mAction == "Create") {
                var dir = Settings.GetProjectFolder();
                if (dir == null) {
                    alert(VECleaner.kTranslator.mData.HOST_ActionSafetyCheck_msg1);
                }
                else if (ColorGradeUtils.HasLookUpImageEffect()) {
                    var name = TemplateConvertionTools.kLUTSelectWindow.mName.text;
                    var comp = app.project.items.addComp(name.length == 0 ? "filter" : name, 512, 512, 1, 1, 25);
                    var lutFile = new File(TemplateConvertionTools.kLUTSelectWindow.lutPath());
                    var impOpt = new ImportOptions(lutFile);
                    var inputFileItem = app.project.importFile(impOpt);
                    var lutLayer = comp.layers.add(inputFileItem);
                    lutLayer.enabled = false;
                    var adjustmentLayer = comp.layers.addSolid([0, 0, 0], "filter", 512, 512, 1);
                    adjustmentLayer.adjustmentLayer = true;
                    var effect = adjustmentLayer.effect.addProperty(ColorGradeUtils.kLookUpImageName);
                    var inputLayerProp = effect.property("VE_Look_Up_Image-0002");
                    inputLayerProp.setValue(2);
                    comp.openInViewer();
                }
            }
            return true;
        };
        TemplateConvertionTools.kVersionConvertWindow = null;
        TemplateConvertionTools.kLUTSelectWindow = null;
        TemplateConvertionTools.kEditFilterConfig = "{\"settings\":{\"attr\":1},\"description\":\"f1\",\"version\":\"2.0.0.release\",\"uuid\":\"1a025ea0-4cca-42b6-b811-fdebb099e345\",\"size\":[512,512],\"duration\":30,\"fps\":30,\"type\":1024,\"main\":\"comp0\",\"ui_version\":\"2.0\",\"mod_type\":2,\"comps\":[{\"name\":\"comp0\",\"duration\":30,\"fps\":30,\"size\":[512,512],\"bg\":\"#ff000000\",\"layers\":[{\"uuid\":\"layer_3\",\"ui_key\":\"\",\"ui_extra\":\"\",\"source\":\"assetkey1\",\"type\":129,\"blend\":0,\"matte\":0,\"resample\":0,\"enabled\":false,\"stretch\":1.0,\"range\":[0,0,30,30],\"mask\":{\"index\":0,\"data\":[]},\"effects\":[],\"layerStyles\":[],\"transform\":{\"p\":[256.0,256.0],\"a\":[256.0,256.0],\"s\":[1.0,1.0],\"t\":1.0,\"r\":0.0}},{\"uuid\":\"layer_2\",\"ui_key\":\"\",\"ui_extra\":\"\",\"source\":\"assetkey0\",\"type\":577,\"blend\":0,\"matte\":0,\"resample\":0,\"enabled\":true,\"stretch\":1.0,\"range\":[0,0,30,30],\"mask\":{\"index\":0,\"data\":[]},\"effects\":[{\"name\":\"VE_Look_Up_Image\",\"data\":{\"layer\":\"layer_3\",\"type\":1,\"intensity\":100.0}}],\"layerStyles\":[],\"transform\":{\"p\":[256.0,256.0],\"a\":[256.0,256.0],\"s\":[1.0,1.0],\"t\":1.0,\"r\":0.0}}]}],\"assets\":[{\"key\":\"assetkey1\",\"ui_key\":\"\",\"ui_extra\":\"\",\"name\":\"asset2.png\",\"type\":1,\"num\":0,\"size\":[512,512]},{\"key\":\"assetkey0\",\"ui_key\":\"\",\"ui_extra\":\"\",\"name\":\"#ffffff\",\"type\":4,\"num\":0,\"size\":[512,512]}],\"ui_group\":[]}";
        return TemplateConvertionTools;
    }());
    var PathInfo = (function () {
        function PathInfo() {
            this.mHandle1 = null;
            this.mHandle2 = null;
        }
        PathInfo.prototype.getPoint = function (t) {
            if (t == 0) {
                return this.mPoint1;
            }
            else if (t == 1) {
                return this.mPoint2;
            }
            var mt = 1.0 - t;
            if (this.mHandle1 != null && this.mHandle2 != null) {
                var mt2 = mt * mt, t2 = t * t, a = mt2 * mt, b = mt2 * t * 3.0, c = mt * t2 * 3.0, d = t * t2;
                return new Vec2(a * this.mPoint1.mX + b * this.mHandle1.mX + c * this.mHandle2.mX + d * this.mPoint2.mX, a * this.mPoint1.mY + b * this.mHandle1.mY + c * this.mHandle2.mY + d * this.mPoint2.mY);
            }
            else {
                return new Vec2(mt * this.mPoint1.mX + t * this.mPoint2.mX, mt * this.mPoint1.mY + t * this.mPoint2.mY);
            }
        };
        PathInfo.prototype.offset = function (v) {
            this.mPoint1.mX += v.mX;
            this.mPoint1.mY += v.mY;
            this.mPoint2.mX += v.mX;
            this.mPoint2.mY += v.mY;
            if (this.mHandle1) {
                this.mHandle1.mX += v.mX;
                this.mHandle1.mY += v.mY;
            }
            if (this.mHandle2) {
                this.mHandle2.mX += v.mX;
                this.mHandle2.mY += v.mY;
            }
        };
        PathInfo.prototype.bounds = function () {
            var minPoint = new Vec2(10000000, 10000000);
            var maxPoint = new Vec2(-10000000, -10000000);
            if (this.mHandle1 != null && this.mHandle2 != null) {
                for (var i = 0; i <= 20; i++) {
                    var segment = this.getPoint(i / 20.0);
                    minPoint.mX = Math.min(minPoint.mX, segment.mX);
                    minPoint.mY = Math.min(minPoint.mY, segment.mY);
                    maxPoint.mX = Math.max(maxPoint.mX, segment.mX);
                    maxPoint.mY = Math.max(maxPoint.mY, segment.mY);
                }
            }
            else {
                minPoint.mX = Math.min(this.mPoint1.mX, this.mPoint2.mX);
                minPoint.mY = Math.min(this.mPoint1.mY, this.mPoint2.mY);
                maxPoint.mX = Math.max(this.mPoint1.mX, this.mPoint2.mX);
                maxPoint.mY = Math.max(this.mPoint1.mY, this.mPoint2.mY);
            }
            return [minPoint.mX, maxPoint.mX, minPoint.mY, maxPoint.mY];
        };
        return PathInfo;
    }());
    var ShapeInfo = (function () {
        function ShapeInfo() {
            this.mPaths = [];
        }
        ShapeInfo.prototype.bounds = function () {
            if (this.mPaths.length == 0) {
                return [0, 0, 0, 0];
            }
            var left = 10000000;
            var right = -10000000;
            var top = 10000000;
            var bottom = -10000000;
            for (var s = 0; s < this.mPaths.length; s++) {
                var b = this.mPaths[s].bounds();
                left = Math.min(b[0], left);
                right = Math.max(b[1], right);
                top = Math.min(b[2], top);
                bottom = Math.max(b[3], bottom);
            }
            return [left, right, top, bottom];
        };
        ShapeInfo.prototype.offset = function (v) {
            for (var p = 0; p < this.mPaths.length; p++) {
                this.mPaths[p].offset(v);
            }
        };
        ShapeInfo.prototype.toMaskShape = function (shapeObj) {
            var vertices = [];
            var outTangents = [];
            var inTangents = [];
            for (var p = 0; p < this.mPaths.length; p++) {
                var path = this.mPaths[p];
                vertices.push([path.mPoint1.mX, path.mPoint1.mY]);
                outTangents.push([0, 0]);
                inTangents.push([0, 0]);
            }
            shapeObj.vertices = vertices;
            for (var p = 0; p < this.mPaths.length; p++) {
                var path = this.mPaths[p];
                if (path.mHandle1 != null) {
                    outTangents[p][0] = path.mHandle1.mX - path.mPoint1.mX;
                    outTangents[p][1] = path.mHandle1.mY - path.mPoint1.mY;
                }
                if (path.mHandle2 != null) {
                    if (p == this.mPaths.length - 1) {
                        inTangents[0][0] = path.mHandle2.mX - this.mPaths[0].mPoint1.mX;
                        inTangents[0][1] = path.mHandle2.mY - this.mPaths[0].mPoint1.mY;
                    }
                    else {
                        inTangents[p + 1][0] = path.mHandle2.mX - this.mPaths[p + 1].mPoint1.mX;
                        inTangents[p + 1][1] = path.mHandle2.mY - this.mPaths[p + 1].mPoint1.mY;
                    }
                }
            }
            shapeObj.outTangents = outTangents;
            shapeObj.inTangents = inTangents;
        };
        return ShapeInfo;
    }());
    var CompoundShapeInfo = (function () {
        function CompoundShapeInfo() {
            this.clear();
        }
        CompoundShapeInfo.prototype.clear = function () {
            this.mShapes = [];
            this.mLastPoint = null;
            this.mLastHandle = null;
        };
        CompoundShapeInfo.prototype.offset = function (v) {
            for (var p = 0; p < this.mShapes.length; p++) {
                this.mShapes[p].offset(v);
            }
        };
        CompoundShapeInfo.prototype.moveTo = function (x, y) {
            var shape = new ShapeInfo();
            this.mShapes.push(shape);
            this.mLastPoint = new Vec2(x, y);
            this.mLastHandle = null;
        };
        CompoundShapeInfo.prototype.lineTo = function (x, y) {
            if (this.mShapes.length > 0) {
                if (this.mLastPoint) {
                    var path = new PathInfo();
                    path.mPoint1 = this.mLastPoint;
                    path.mPoint2 = new Vec2(x, y);
                    this.mShapes[this.mShapes.length - 1].mPaths.push(path);
                }
                this.mLastPoint = new Vec2(x, y);
                this.mLastHandle = null;
            }
        };
        CompoundShapeInfo.prototype.bezierTo = function (x, y, cx1, cy1, cx2, cy2) {
            if (this.mShapes.length > 0) {
                if (this.mLastPoint) {
                    var path = new PathInfo();
                    path.mPoint1 = this.mLastPoint;
                    path.mPoint2 = new Vec2(x, y);
                    path.mHandle1 = new Vec2(cx1, cy1);
                    path.mHandle2 = new Vec2(cx2, cy2);
                    this.mShapes[this.mShapes.length - 1].mPaths.push(path);
                }
                this.mLastPoint = new Vec2(x, y);
                this.mLastHandle = null;
            }
        };
        CompoundShapeInfo.prototype.lastShape = function () {
            if (this.mShapes.length > 0) {
                return this.mShapes[this.mShapes.length - 1];
            }
            return null;
        };
        CompoundShapeInfo.prototype.bounds = function () {
            if (this.mShapes.length == 0) {
                return [0, 0, 0, 0];
            }
            var left = 10000000;
            var right = -10000000;
            var top = 10000000;
            var bottom = -10000000;
            for (var s = 0; s < this.mShapes.length; s++) {
                var b = this.mShapes[s].bounds();
                left = Math.min(b[0], left);
                right = Math.max(b[1], right);
                top = Math.min(b[2], top);
                bottom = Math.max(b[3], bottom);
            }
            return [left, right, top, bottom];
        };
        CompoundShapeInfo.FromShape = function (shape) {
            var result = new CompoundShapeInfo();
            if (shape.vertices.length >= 3 && shape.closed) {
                var vertices = shape.vertices;
                var inTangents = shape.inTangents;
                var outTangents = shape.outTangents;
                for (var i_1 = 0; i_1 < vertices.length; i_1++) {
                    inTangents[i_1] = [inTangents[i_1][0] + vertices[i_1][0], inTangents[i_1][1] + vertices[i_1][1]];
                    outTangents[i_1] = [outTangents[i_1][0] + vertices[i_1][0], outTangents[i_1][1] + vertices[i_1][1]];
                }
                ;
                result.moveTo(vertices[0][0], vertices[0][1]);
                for (var i = 1; i < vertices.length; i++) {
                    if (outTangents[i - 1][0] == vertices[i - 1][0] && outTangents[i - 1][1] == vertices[i - 1][1] && inTangents[i][0] == vertices[i][0] && inTangents[i][1] == vertices[i][1]) {
                        result.lineTo(vertices[i][0], vertices[i][1]);
                    }
                    else {
                        result.bezierTo(vertices[i][0], vertices[i][1], outTangents[i - 1][0], outTangents[i - 1][1], inTangents[i][0], inTangents[i][1]);
                    }
                }
                ;
                if (outTangents[outTangents.length - 1][0] == vertices[outTangents.length - 1][0] && outTangents[outTangents.length - 1][1] == vertices[outTangents.length - 1][1] && inTangents[0][0] == vertices[0][1] && inTangents[0][0] == vertices[0][1]) {
                    result.lineTo(vertices[0][0], vertices[0][1]);
                }
                else {
                    result.bezierTo(vertices[0][0], vertices[0][1], outTangents[outTangents.length - 1][0], outTangents[outTangents.length - 1][1], inTangents[0][0], inTangents[0][1]);
                }
            }
            return result;
        };
        return CompoundShapeInfo;
    }());
    var CropTools = (function () {
        function CropTools() {
        }
        CropTools.CalculateComplexMaskSize = function (thisComp, baseLayer, mask) {
            var keyTimes = [];
            if (mask.maskShape.numKeys > 0) {
                for (var k = 1; k <= mask.maskShape.numKeys; k++) {
                    keyTimes.push(mask.maskShape.keyTime(k));
                }
            }
            else {
                keyTimes.push(0);
            }
            var totalRectSize = [10000000, -10000000, 10000000, -10000000];
            for (var k = 0; k < keyTimes.length; k++) {
                var t = keyTimes[k];
                var shape = mask.maskShape.valueAtTime(t, false);
                var result = CompoundShapeInfo.FromShape(shape);
                var rectSize = result.bounds();
                totalRectSize[0] = Math.min(totalRectSize[0], rectSize[0]);
                totalRectSize[1] = Math.max(totalRectSize[1], rectSize[1]);
                totalRectSize[2] = Math.min(totalRectSize[2], rectSize[2]);
                totalRectSize[3] = Math.max(totalRectSize[3], rectSize[3]);
            }
            totalRectSize[0] = Math.floor(totalRectSize[0]);
            totalRectSize[1] = Math.ceil(totalRectSize[1]);
            totalRectSize[2] = Math.floor(totalRectSize[2]);
            totalRectSize[3] = Math.ceil(totalRectSize[3]);
            return totalRectSize;
        };
        CropTools.ExpendSize = function (totalRectSize, doPadding, pad) {
            var left = totalRectSize[0];
            var right = totalRectSize[1];
            var top = totalRectSize[2];
            var bottom = totalRectSize[3];
            var xSize = Math.ceil(right - left);
            var ySize = Math.ceil(bottom - top);
            xSize = Math.max(xSize, 4);
            ySize = Math.max(ySize, 4);
            var xCenter = left + (xSize * 0.5);
            var yCenter = top + (ySize * 0.5);
            if (doPadding == true) {
                xSize = xSize + (pad * 2.0);
                ySize = ySize + (pad * 2.0);
            }
            return [xSize, ySize, xCenter, yCenter];
        };
        CropTools.CopyMask = function (fromLayer, maskIdx, toLayer, offset) {
            var mask = fromLayer.mask.property(maskIdx);
            var maskShape = mask.maskShape;
            var newMask = toLayer.mask.addProperty("ADBE Mask Atom");
            var newMaskShape = newMask.maskShape;
            if (maskShape.numKeys > 0) {
                for (var k = 1; k <= maskShape.numKeys; k++) {
                    newMaskShape.addKey(maskShape.keyTime(k));
                    var result = CompoundShapeInfo.FromShape(maskShape.keyValue(k));
                    result.offset(offset);
                    if (result.mShapes.length > 0) {
                        var newShape = newMaskShape.keyValue(k);
                        result.mShapes[0].toMaskShape(newShape);
                        newMaskShape.setValueAtKey(k, newShape);
                    }
                }
            }
            else {
                var result = CompoundShapeInfo.FromShape(maskShape.value);
                result.offset(offset);
                if (result.mShapes.length > 0) {
                    var newShape = newMaskShape.value;
                    result.mShapes[0].toMaskShape(newShape);
                    newMaskShape.setValue(newShape);
                }
            }
            for (var k = 1; k <= mask.numProperties; k += 1) {
                var prop = mask.property(k);
                var newProp = newMask.property(k);
                if (prop.propertyType == PropertyType.PROPERTY && prop.matchName != "ADBE Mask Shape") {
                    AnimationUtils.CopyPropertyAnimation(prop, newProp);
                }
            }
            newMask.maskMode = mask.maskMode;
            newMask.inverted = mask.inverted;
            newMask.locked = mask.locked;
        };
        CropTools.CropLayer = function (thisComp, baseLayer, newName, size, center, inTime, outTime, timeType) {
            var resultLayer = baseLayer.duplicate();
            var duplicateLayer = baseLayer.duplicate();
            var dur = outTime - inTime;
            if (timeType == 0) {
                dur = baseLayer.outPoint - baseLayer.inPoint;
            }
            duplicateLayer.inPoint = inTime;
            duplicateLayer.outPoint = outTime;
            var duplicateLayerIndex = duplicateLayer.index;
            var newPrecomp = thisComp.layers.precompose([duplicateLayerIndex], newName, true);
            newPrecomp.duration = dur;
            newPrecomp.displayStartTime = thisComp.displayStartTime + inTime;
            newPrecomp.width = size[0];
            newPrecomp.height = size[1];
            var precompLayer = thisComp.selectedLayers[0];
            precompLayer.remove();
            resultLayer.replaceSource(newPrecomp, true);
            var offset = [size[0] * 0.5 - center[0], size[1] * 0.5 - center[1]];
            if (resultLayer.anchorPoint.numKeys > 0) {
                if (resultLayer.threeDLayer) {
                    for (var k = 1; k <= baseLayer.anchorPoint.numKeys; k++) {
                        var anchor = baseLayer.anchorPoint.keyValue(k);
                        resultLayer.anchorPoint.setValueAtKey(k, [offset[0] + anchor[0], offset[1] + anchor[1], anchor[2]]);
                    }
                }
                else {
                    for (var k = 1; k <= baseLayer.anchorPoint.numKeys; k++) {
                        var anchor = baseLayer.anchorPoint.keyValue(k);
                        resultLayer.anchorPoint.setValueAtKey(k, [offset[0] + anchor[0], offset[1] + anchor[1]]);
                    }
                }
            }
            else {
                var anchor = baseLayer.anchorPoint.value;
                if (resultLayer.threeDLayer) {
                    resultLayer.anchorPoint.setValue([offset[0] + anchor[0], offset[1] + anchor[1], anchor[2]]);
                }
                else {
                    resultLayer.anchorPoint.setValue([offset[0] + anchor[0], offset[1] + anchor[1]]);
                }
            }
            resultLayer.startTime = inTime;
            var newPrecompLayer = newPrecomp.layer(1);
            newPrecompLayer.threeDLayer = false;
            AnimationUtils.RemoveLayerAnimation(newPrecompLayer);
            DomUtils.RemoveLayerAllEffects(newPrecompLayer);
            DomUtils.RemoveLayerAllStyles(newPrecompLayer);
            DomUtils.RemoveLayerAllMasks(newPrecompLayer);
            newPrecompLayer.startTime = 0 - (newPrecompLayer.inPoint - newPrecompLayer.startTime);
            newPrecompLayer.outPoint = newPrecompLayer.inPoint + dur;
            newPrecompLayer.opacity.setValue(100);
            newPrecompLayer.zRotation.setValue(0);
            newPrecompLayer.scale.setValue([100, 100]);
            newPrecompLayer.anchorPoint.setValue(center);
            newPrecompLayer.position.setValue([size[0] * 0.5, size[1] * 0.5]);
            return resultLayer;
        };
        CropTools.CropLayerToFitMasks = function (pad) {
            var layer = DomUtils.GetFirstSelectedLayer();
            if (layer instanceof AVLayer) {
                var numMasks = layer.mask.numProperties;
                if (numMasks > 0) {
                    var thisComp = layer.containingComp;
                    var inTime = thisComp.time;
                    var outTime = thisComp.time;
                    var timeType = 2;
                    if (timeType == 1) {
                        inTime = layer.inPoint;
                        outTime = layer.outPoint;
                    }
                    if (timeType == 2) {
                        inTime = thisComp.workAreaStart;
                        outTime = thisComp.workAreaStart + thisComp.workAreaDuration;
                        inTime = Math.max(layer.inPoint, inTime);
                        outTime = Math.min(layer.outPoint, outTime);
                    }
                    var totalRectSize = [10000000, -10000000, 10000000, -10000000];
                    var doPadding = pad >= 1;
                    var hasValidMasks = false;
                    for (var i = 1; i <= numMasks; i += 1) {
                        var mask = layer.mask.property(i);
                        var shape = mask.maskShape.value;
                        if (shape.vertices.length < 2) {
                            continue;
                        }
                        hasValidMasks = true;
                        var bounds = CropTools.CalculateComplexMaskSize(thisComp, layer, mask);
                        totalRectSize[0] = Math.min(totalRectSize[0], bounds[0]);
                        totalRectSize[1] = Math.max(totalRectSize[1], bounds[1]);
                        totalRectSize[2] = Math.min(totalRectSize[2], bounds[2]);
                        totalRectSize[3] = Math.max(totalRectSize[3], bounds[3]);
                    }
                    var xSize = totalRectSize[1] - totalRectSize[0];
                    var ySize = totalRectSize[3] - totalRectSize[2];
                    var finalSize = CropTools.ExpendSize(totalRectSize, doPadding, pad);
                    xSize = finalSize[0];
                    ySize = finalSize[1];
                    var xCenter = finalSize[2];
                    var yCenter = finalSize[3];
                    var newLayer = CropTools.CropLayer(thisComp, layer, layer.name, [xSize, ySize], [xCenter, yCenter], inTime, outTime, timeType);
                    DomUtils.RemoveLayerAllMasks(newLayer);
                    var left = -totalRectSize[0], top = -totalRectSize[2];
                    if (doPadding) {
                        left += pad;
                        top += pad;
                    }
                    for (var i = 1; i <= numMasks; i += 1) {
                        CropTools.CopyMask(layer, i, newLayer, new Vec2(left, top));
                    }
                }
            }
            return true;
        };
        CropTools.SplitLayerMasks = function (pad, keepMask) {
            var layer = DomUtils.GetFirstSelectedLayer();
            if (layer instanceof AVLayer) {
                var numMasks = layer.mask.numProperties;
                if (numMasks > 0) {
                    var thisComp = layer.containingComp;
                    var inTime = thisComp.time;
                    var outTime = thisComp.time;
                    var timeType = 2;
                    if (timeType == 1) {
                        inTime = layer.inPoint;
                        outTime = layer.outPoint;
                    }
                    if (timeType == 2) {
                        inTime = thisComp.workAreaStart;
                        outTime = thisComp.workAreaStart + thisComp.workAreaDuration;
                        inTime = Math.max(layer.inPoint, inTime);
                        outTime = Math.min(layer.outPoint, outTime);
                    }
                    var totalRectSize = [];
                    var doPadding = pad >= 1;
                    for (var i = 1; i <= numMasks; i += 1) {
                        var mask = layer.mask.property(i);
                        var shape = mask.maskShape.value;
                        if (shape.vertices.length < 2 || !shape.closed) {
                            continue;
                        }
                        totalRectSize = CropTools.CalculateComplexMaskSize(thisComp, layer, mask);
                        var xSize = totalRectSize[1] - totalRectSize[0];
                        var ySize = totalRectSize[3] - totalRectSize[2];
                        var finalSize = CropTools.ExpendSize(totalRectSize, doPadding, pad);
                        xSize = finalSize[0];
                        ySize = finalSize[1];
                        var xCenter = finalSize[2];
                        var yCenter = finalSize[3];
                        var newName = layer.name + "_" + i;
                        var newLayer = CropTools.CropLayer(thisComp, layer, newName, [xSize, ySize], [xCenter, yCenter], inTime, outTime, timeType);
                        DomUtils.RemoveLayerAllMasks(newLayer);
                        if (keepMask) {
                            var left = -totalRectSize[0], top = -totalRectSize[2];
                            if (doPadding) {
                                left += pad;
                                top += pad;
                            }
                            CropTools.CopyMask(layer, i, newLayer, new Vec2(left, top));
                        }
                    }
                    return true;
                }
            }
            return false;
        };
        CropTools.CropLayer2FitMasks = function () {
            var padStr = prompt(VECleaner.kTranslator.mData.HOST_CropTools_BorderSpace_Description, "2", VECleaner.kTranslator.mData.HOST_CropTools_BorderSpace);
            var pad = parseFloat(padStr);
            if (isNaN(pad)) {
                pad = 0;
            }
            else {
                pad = Math.min(100, Math.max(0, Math.floor(pad)));
            }
            return CropTools.CropLayerToFitMasks(pad);
        };
        CropTools.SplitLayerMasksKeepMask = function () {
            var padStr = prompt(VECleaner.kTranslator.mData.HOST_CropTools_BorderSpace_Description, "2", VECleaner.kTranslator.mData.HOST_CropTools_BorderSpace);
            var pad = parseFloat(padStr);
            if (isNaN(pad)) {
                pad = 0;
            }
            else {
                pad = Math.min(100, Math.max(0, Math.floor(pad)));
            }
            return CropTools.SplitLayerMasks(pad, true);
        };
        CropTools.SplitLayerMasksWithoutMask = function () {
            var padStr = prompt(VECleaner.kTranslator.mData.HOST_CropTools_BorderSpace_Description, "2", VECleaner.kTranslator.mData.HOST_CropTools_BorderSpace);
            var pad = parseFloat(padStr);
            if (isNaN(pad)) {
                pad = 0;
            }
            else {
                pad = Math.min(100, Math.max(0, Math.floor(pad)));
            }
            return CropTools.SplitLayerMasks(pad, false);
        };
        CropTools.SimpleCrop = function () {
            return true;
        };
        return CropTools;
    }());
    var ImageThumbnailSettingPanel = (function () {
        function ImageThumbnailSettingPanel() {
            var self = this;
            this.mWin = new Window("dialog", "Image Settings", undefined, { resizeable: true });
            this.mWin.orientation = "column";
            this.mWin.minimumSize[0] = 400;
            var outputGr = this.mWin.add("panel", undefined, "Output Image File");
            outputGr.orientation = "row";
            outputGr.alignment = ["fill", "top"];
            var outputLabel = outputGr.add("statictext", undefined, "Output File:");
            outputLabel.alignment = ["left", "center"];
            this.mOutputPath = outputGr.add("edittext", undefined, "", { readonly: true });
            this.mOutputPath.alignment = ["fill", "center"];
            this.mSelectOutput = outputGr.add("button", undefined, "...");
            this.mSelectOutput.alignment = ["right", "center"];
            this.mSelectOutput.onClick = function () {
                self.selectPNGFile();
            };
            var settingGr = this.mWin.add("panel", undefined, "Settings");
            settingGr.orientation = "row";
            settingGr.alignment = ["fill", "top"];
            var scaleGr = settingGr.add("group");
            scaleGr.orientation = "row";
            scaleGr.alignment = ["fill", "fill"];
            var scaleLabel = scaleGr.add("statictext", undefined, "Scale:");
            scaleLabel.alignment = ["left", "center"];
            this.mScale = scaleGr.add("dropdownlist", undefined, ["100%", "50%", "25%", "10%"]);
            this.mScale.alignment = ["fill", "center"];
            this.mScale.selection = 0;
            this.mConvert = this.mWin.add("button", undefined, "Make");
            this.mConvert.alignment = ["fill", "top"];
            this.mConvert.onClick = function () {
                var comp = DomUtils.GetCurrentComp();
                if (comp == null) {
                    alert("Please select the comp you want to render!");
                }
                else {
                    self.mAction = "OK";
                    self.close();
                }
            };
        }
        ImageThumbnailSettingPanel.prototype.selectPNGFile = function () {
            var f = File.saveDialog("Output PNG file", "PNG file:*.png");
            if (f) {
                var dotIdx = f.displayName.lastIndexOf(".");
                if (dotIdx == -1 || f.displayName.substr(dotIdx).toLocaleLowerCase() != ".png") {
                    this.mOutputPath.text = f.fsName + ".png";
                }
                else {
                    this.mOutputPath.text = f.fsName;
                }
            }
        };
        ImageThumbnailSettingPanel.prototype.update = function () {
            this.mWin.layout.layout(true);
        };
        ImageThumbnailSettingPanel.prototype.show = function () {
            this.mAction = "Cancel";
            var panel = this.mWin;
            panel.onResizing = panel.onResize = function () {
                panel.layout.resize();
            };
            panel.layout.layout(true);
            panel.layout.resize();
            panel.show();
        };
        ImageThumbnailSettingPanel.prototype.close = function () {
            if (this.mWin) {
                this.mWin.close();
            }
        };
        ImageThumbnailSettingPanel.ConvertIndexToScale = function (index) {
            switch (index) {
                case 0: return 1;
                case 1: return 2;
                case 2: return 4;
                case 3: return 10;
                default: return 1;
            }
        };
        ImageThumbnailSettingPanel.prototype.outputPath = function () {
            return this.mOutputPath.text.replace(/\\/g, "\/");
        };
        ImageThumbnailSettingPanel.prototype.scale = function () {
            return ImageThumbnailSettingPanel.ConvertIndexToScale(this.mScale.selection.index);
        };
        return ImageThumbnailSettingPanel;
    }());
    var EditTemplateType;
    (function (EditTemplateType) {
        EditTemplateType[EditTemplateType["kVideoEffect"] = 0] = "kVideoEffect";
        EditTemplateType[EditTemplateType["kVideoTransition"] = 1] = "kVideoTransition";
    })(EditTemplateType || (EditTemplateType = {}));
    var EditTemplateStructure = (function () {
        function EditTemplateStructure(comp) {
            this.mAssets = [];
            this.collectAssets(comp);
        }
        EditTemplateStructure.prototype.collectAssets = function (comp) {
            for (var l = 1, nl = comp.numLayers; l <= nl; l++) {
                var layer = comp.layer(l);
                if (layer instanceof AVLayer) {
                    var lSource = layer.source;
                    if (lSource instanceof CompItem) {
                        this.collectAssets(lSource);
                    }
                    else {
                        var types = LayerTypeUtils.GetlayerType(layer);
                        if (types & LayerTypes.kStillLayer) {
                            var footageItem = lSource;
                            if (footageItem != null && footageItem.name.indexOf("VE_video") == 0) {
                                this.addAsset(footageItem);
                            }
                        }
                    }
                }
            }
        };
        EditTemplateStructure.prototype.addAsset = function (footage) {
            for (var f = 0; f < this.mAssets.length; f++) {
                if (this.mAssets[f] != null && this.mAssets[f].id == footage.id) {
                    return;
                }
            }
            this.mAssets.push(footage);
        };
        EditTemplateStructure.prototype.assetWithPrefix = function (prefix) {
            for (var f = 0; f < this.mAssets.length; f++) {
                if (this.mAssets[f] != null && this.mAssets[f].name.indexOf(prefix) == 0) {
                    return this.mAssets[f];
                }
            }
            return null;
        };
        EditTemplateStructure.prototype.editableAssets = function (type) {
            if (type == EditTemplateType.kVideoTransition) {
                var f1 = this.assetWithPrefix("VE_video1");
                var f2 = this.assetWithPrefix("VE_video2");
                if (f1 != null && f2 != null) {
                    return [f1, f2];
                }
            }
            else {
                var f1 = this.assetWithPrefix("VE_video1");
                if (f1 != null) {
                    return [f1];
                }
            }
            return [];
        };
        EditTemplateStructure.prototype.changePlaceholders = function (type, placeholders) {
            var assets = this.editableAssets(type);
            if (assets.length > 0 && assets.length == placeholders.length) {
                for (var i = 0; i < assets.length; i++) {
                    if (placeholders[i] != null) {
                        assets[i].setProxy(placeholders[i]);
                    }
                }
            }
        };
        EditTemplateStructure.prototype.removePlaceholders = function (type) {
            var assets = this.editableAssets(type);
            for (var i = 0; i < assets.length; i++) {
                if (assets[i] != null) {
                    assets[i].setProxyToNone();
                }
            }
        };
        EditTemplateStructure.prototype.isValid = function (type) {
            var fs = this.editableAssets(type);
            return fs.length != 0;
        };
        return EditTemplateStructure;
    }());
    var EditTemplateRenderSettingPanel = (function () {
        function EditTemplateRenderSettingPanel(type) {
            var self = this;
            this.mPlaceholderFiles = [];
            this.mTemplateType = type;
            this.mWin = new Window("dialog", "Edit Template Thumbnail", undefined, { resizeable: true });
            this.mWin.orientation = "column";
            this.mWin.minimumSize[0] = 500;
            var filesGr = this.mWin.add("panel", undefined, "Files");
            filesGr.orientation = "column";
            filesGr.alignment = ["fill", "top"];
            if (type == EditTemplateType.kVideoTransition) {
                this.mPlaceholderFiles.push(this.addPathSelector(filesGr, 1));
                this.mPlaceholderFiles.push(this.addPathSelector(filesGr, 2));
            }
            else {
                this.mPlaceholderFiles.push(this.addPathSelector(filesGr, 1));
            }
            var outputGr = this.mWin.add("panel", undefined, "Output GIF File");
            outputGr.orientation = "row";
            outputGr.alignment = ["fill", "top"];
            var outputLabel = outputGr.add("statictext", undefined, "Output File:");
            outputLabel.alignment = ["left", "center"];
            this.mOutputPath = outputGr.add("edittext", undefined, "", { readonly: true });
            this.mOutputPath.alignment = ["fill", "center"];
            this.mSelectOutput = outputGr.add("button", undefined, "...");
            this.mSelectOutput.alignment = ["right", "center"];
            this.mSelectOutput.onClick = function () {
                self.selectGIFFile();
            };
            var settingGr = this.mWin.add("panel", undefined, "Settings");
            settingGr.orientation = "row";
            settingGr.alignment = ["fill", "top"];
            var sizeGr = settingGr.add("group");
            sizeGr.orientation = "row";
            sizeGr.alignment = ["fill", "fill"];
            var sizeLabel = sizeGr.add("statictext", undefined, "Size:");
            sizeLabel.alignment = ["left", "center"];
            this.mSizeType = sizeGr.add("dropdownlist", undefined, [VECleaner.kTranslator.mData.HOST_ThumbnailTools_SizeComp, VECleaner.kTranslator.mData.HOST_ThumbnailTools_SizePlaceholder, VECleaner.kTranslator.mData.HOST_ThumbnailTools_SizePlaceholder2]);
            this.mSizeType.alignment = ["fill", "center"];
            this.mSizeType.selection = 1;
            var scaleGr = settingGr.add("group");
            scaleGr.orientation = "row";
            scaleGr.alignment = ["right", "fill"];
            var scaleLabel = scaleGr.add("statictext", undefined, "Scale:");
            scaleLabel.alignment = ["left", "center"];
            this.mScale = scaleGr.add("dropdownlist", undefined, ["100%", "75%", "50%", "25%", "10%"]);
            this.mScale.alignment = ["fill", "center"];
            this.mScale.selection = 2;
            var fpsGr = settingGr.add("group");
            fpsGr.orientation = "row";
            fpsGr.alignment = ["right", "fill"];
            var fpsLabel = fpsGr.add("statictext", undefined, "FPS:");
            fpsLabel.alignment = ["left", "center"];
            this.mFps = fpsGr.add("dropdownlist", undefined, ["100%", "75%", "50%", "25%", "10%"]);
            this.mFps.alignment = ["fill", "center"];
            this.mFps.selection = 2;
            var speedGr = settingGr.add("group");
            speedGr.orientation = "row";
            speedGr.alignment = ["right", "fill"];
            var speedLabel = speedGr.add("statictext", undefined, "Speed:");
            speedLabel.alignment = ["left", "center"];
            this.mSpeed = speedGr.add("dropdownlist", undefined, ["50%", "100%", "200%", "300%", "400%"]);
            this.mSpeed.alignment = ["fill", "center"];
            this.mSpeed.selection = 1;
            this.mConvert = this.mWin.add("button", undefined, "Make");
            this.mConvert.alignment = ["fill", "top"];
            this.mConvert.onClick = function () {
                var comp = DomUtils.GetCurrentComp();
                if (comp == null) {
                    alert("Please select the comp you want to render!");
                }
                else {
                    self.mAction = "OK";
                    self.close();
                }
            };
        }
        EditTemplateRenderSettingPanel.prototype.getPlaceholderFiles = function () {
            var files = [];
            for (var i = 0; i < this.mPlaceholderFiles.length; i++) {
                var file = new File(this.mPlaceholderFiles[i].text);
                if (file.exists) {
                    files.push(file);
                }
                else {
                    files.push(null);
                }
            }
            return files;
        };
        EditTemplateRenderSettingPanel.GetFirstPlaceholderFiles = function (files) {
            for (var i = 0; i < files.length; i++) {
                if (files[i] != null) {
                    return files[i];
                }
            }
            return null;
        };
        EditTemplateRenderSettingPanel.prototype.selectGIFFile = function () {
            var f = File.saveDialog("Output GIF file", "GIF file:*.gif");
            if (f) {
                var dotIdx = f.displayName.lastIndexOf(".");
                if (dotIdx == -1 || f.displayName.substr(dotIdx).toLocaleLowerCase() != ".gif") {
                    this.mOutputPath.text = f.fsName + ".gif";
                }
                else {
                    this.mOutputPath.text = f.fsName;
                }
            }
        };
        EditTemplateRenderSettingPanel.prototype.addPathSelector = function (gr, idx) {
            var outputGr = gr.add("group");
            outputGr.orientation = "row";
            outputGr.alignment = ["fill", "top"];
            var outputLabel = outputGr.add("statictext", undefined, "Placeholder File " + idx + ":");
            outputLabel.alignment = ["left", "center"];
            var outputPath = outputGr.add("edittext", undefined, "", { readonly: true });
            outputPath.alignment = ["fill", "center"];
            var selectOutput = outputGr.add("button", undefined, "...");
            selectOutput.alignment = ["right", "center"];
            selectOutput.onClick = function () {
                var f = File.openDialog("Placeholder File " + idx, "Image file:*.png;*.jpg");
                if (f) {
                    outputPath.text = f.fsName;
                }
            };
            return outputPath;
        };
        EditTemplateRenderSettingPanel.prototype.update = function () {
            this.mWin.layout.layout(true);
        };
        EditTemplateRenderSettingPanel.prototype.show = function () {
            this.mAction = "Cancel";
            var panel = this.mWin;
            panel.onResizing = panel.onResize = function () {
                panel.layout.resize();
            };
            panel.layout.layout(true);
            panel.layout.resize();
            panel.show();
        };
        EditTemplateRenderSettingPanel.prototype.close = function () {
            if (this.mWin) {
                this.mWin.close();
            }
        };
        EditTemplateRenderSettingPanel.prototype.sizeType = function () {
            return this.mSizeType.selection.index;
        };
        EditTemplateRenderSettingPanel.ConvertIndexToPercent = function (index) {
            switch (index) {
                case 0: return 1.0;
                case 1: return 0.75;
                case 2: return 0.5;
                case 3: return 0.25;
                case 4: return 0.1;
                default: return 1.0;
            }
        };
        EditTemplateRenderSettingPanel.ConvertIndexToScale = function (index) {
            switch (index) {
                case 0: return 0.5;
                case 1: return 1.0;
                case 2: return 2.0;
                case 3: return 3.0;
                case 4: return 4.0;
                default: return 1.0;
            }
        };
        EditTemplateRenderSettingPanel.prototype.composeCmd = function (compID, tempCompID, inputFile) {
            if (inputFile === void 0) { inputFile = ""; }
            if (inputFile == undefined || inputFile.length == 0) {
                inputFile = this.mFilePath.text;
            }
            inputFile = inputFile.replace(/\\/g, "\/");
            var outputFile = this.mOutputPath.text.replace(/\\/g, "\/");
            var inputFileObj = new File(inputFile);
            if (!inputFileObj.exists) {
                alert(VECleaner.kTranslator.mData.HOST_AssetTools_GIF2Video_SetVideo);
                return "";
            }
            var ffpath = FFUtils.GetFFmpegBinary();
            ffpath = ffpath.replace(/\\/g, "\/");
            ffpath = ffpath.replace(/%20/g, "\ ");
            var fps = 20;
            var speed = GIFSettingPanel.ConvertIndexToScale(this.mSpeed.selection.index);
            var width = 320;
            var height = 320;
            if ((new File(ffpath)).exists && inputFileObj.exists) {
                var inputFileItem = DomUtils.GetItemByFile(inputFileObj);
                if (inputFileItem == null) {
                    var impOpt = new ImportOptions(inputFileObj);
                    inputFileItem = app.project.importFile(impOpt);
                    fps = Math.round(inputFileItem.frameRate * GIFSettingPanel.ConvertIndexToPercent(this.mFps.selection.index));
                    width = Math.round(inputFileItem.width * GIFSettingPanel.ConvertIndexToPercent(this.mScale.selection.index));
                    height = Math.round(inputFileItem.height * GIFSettingPanel.ConvertIndexToPercent(this.mScale.selection.index));
                    inputFileItem.remove();
                }
                else {
                    fps = Math.round(inputFileItem.frameRate * GIFSettingPanel.ConvertIndexToPercent(this.mFps.selection.index));
                    width = Math.round(inputFileItem.width * GIFSettingPanel.ConvertIndexToPercent(this.mScale.selection.index));
                    height = Math.round(inputFileItem.height * GIFSettingPanel.ConvertIndexToPercent(this.mScale.selection.index));
                }
                var paletteFilePath = Settings.NewCacheAsset(Settings.NewCacheAssetName(".png"));
                var paletteCmd = '"' + ffpath + '" -i "' + inputFile + '" -r ' + fps + ' -vf fps=' + fps + ',scale=' + Math.min(width, height) + ':-1:flags=lanczos,palettegen -y "' + paletteFilePath + '" ';
                var gifCmd = '"' + ffpath + '" -i "' + inputFile + '" -i "' + paletteFilePath + '" -r ' + fps + ' -lavfi fps=' + fps + ',scale=' + Math.min(width, height) + ':-1:flags=lanczos[x];[x]setpts=' + (1.0 / speed) + '*PTS[y];[y][1:v]paletteuse -y "' + outputFile + '" ';
                var json = new JsonWriter();
                json.startObject();
                json.putKey("cmds");
                json.startArray();
                json.putString(paletteCmd);
                json.putString(gifCmd);
                json.endArray();
                json.putKey("file");
                json.putString(inputFile);
                json.putKey("comp");
                json.putNumber(compID);
                json.putKey("tempcomp");
                json.putNumber(tempCompID);
                json.putKey("type");
                json.putNumber(this.mTemplateType);
                json.endObject();
                return json.getContent();
            }
            else {
                return "";
            }
        };
        return EditTemplateRenderSettingPanel;
    }());
    var ThumbnailTools = (function () {
        function ThumbnailTools() {
        }
        ThumbnailTools.CreatePNGThumbnail = function () {
            if (ThumbnailTools.kMakePNGThumbnailWin) {
                ThumbnailTools.kMakePNGThumbnailWin.close();
                ThumbnailTools.kMakePNGThumbnailWin = null;
            }
            ThumbnailTools.kMakePNGThumbnailWin = new ImageThumbnailSettingPanel();
            ThumbnailTools.kMakePNGThumbnailWin.show();
            if (ThumbnailTools.kMakePNGThumbnailWin.mAction == "OK") {
                var comp = DomUtils.GetCurrentComp();
                var scale = ThumbnailTools.kMakePNGThumbnailWin.scale();
                var filePath = ThumbnailTools.kMakePNGThumbnailWin.outputPath();
                alert(scale.toString());
                var file = new File(filePath);
                if (comp) {
                    var currentScale = comp.resolutionFactor;
                    comp.resolutionFactor = [scale, scale];
                    comp.saveFrameToPng(comp.time, file);
                    return true;
                }
                else {
                    return false;
                }
            }
        };
        ThumbnailTools.CreateGIFThumbnail = function () {
            if (ThumbnailTools.kMakeGIFThumbnailWin) {
                ThumbnailTools.kMakeGIFThumbnailWin.close();
                ThumbnailTools.kMakeGIFThumbnailWin = null;
            }
            ThumbnailTools.kMakeGIFThumbnailWin = new GIFSettingPanel(true);
            ThumbnailTools.kMakeGIFThumbnailWin.show();
            if (ThumbnailTools.kMakeGIFThumbnailWin.mAction == "OK") {
                var comp = DomUtils.GetCurrentComp();
                if (comp) {
                    var videoFile = Settings.NewCacheAsset(Settings.NewCacheAssetName(".mov"));
                    RenderUtils.RenderComp(comp, RenderUtils.kNormalVideoRenderTemplate, videoFile);
                    return ThumbnailTools.kMakeGIFThumbnailWin.composeCmd(videoFile);
                }
                else {
                    return "";
                }
            }
            return "";
        };
        ThumbnailTools.CreateGIFThumbnail2 = function (cmd) {
            if (cmd.length > 0) {
                var cmdObj = JSON.parse(cmd);
                if (cmdObj.file) {
                    var file = new File(cmdObj.file);
                    if (file.exists) {
                        file.remove();
                    }
                }
                alert(VECleaner.kTranslator.mData.HOST_AssetTools_GIF2Video_Success);
            }
            else {
                alert(VECleaner.kTranslator.mData.HOST_AssetTools_GIF2Video_Fail);
            }
        };
        ThumbnailTools.CreateEditTemplateThumbnail = function (type) {
            if (ThumbnailTools.kMakeEditTemplateThumbnailWin) {
                ThumbnailTools.kMakeEditTemplateThumbnailWin.close();
                ThumbnailTools.kMakeEditTemplateThumbnailWin = null;
            }
            ThumbnailTools.kMakeEditTemplateThumbnailWin = new EditTemplateRenderSettingPanel(type);
            ThumbnailTools.kMakeEditTemplateThumbnailWin.show();
            if (ThumbnailTools.kMakeEditTemplateThumbnailWin.mAction == "OK") {
                var comp = DomUtils.GetCurrentComp();
                if (comp) {
                    var struct = new EditTemplateStructure(comp);
                    if (struct.isValid(type)) {
                        var placeholders = ThumbnailTools.kMakeEditTemplateThumbnailWin.getPlaceholderFiles();
                        var firstPlaceholder = EditTemplateRenderSettingPanel.GetFirstPlaceholderFiles(placeholders);
                        var width = comp.width;
                        var height = comp.height;
                        var sizeType = ThumbnailTools.kMakeEditTemplateThumbnailWin.sizeType();
                        if (sizeType >= 1 && firstPlaceholder != null) {
                            var img = ScriptUI.newImage(firstPlaceholder.fsName);
                            width = img.size[0];
                            height = img.size[1];
                        }
                        struct.changePlaceholders(type, placeholders);
                        var tempComp = app.project.items.addComp("VE_TEMP_RENDER_COMP", width, height, 1, comp.duration, comp.frameRate);
                        var layer = tempComp.layers.add(comp);
                        if (sizeType == 2) {
                            var scale = Math.max(tempComp.width / layer.width, tempComp.height / layer.height);
                            alert(scale.toString());
                            var w = layer.width * scale, h = layer.height * scale;
                            var offsetW = (w - tempComp.width) * 0.5;
                            var offsetH = (h - tempComp.height) * 0.5;
                            layer.scale.setValue([scale * 100.0, scale * 100.0]);
                            layer.anchorPoint.setValue([0, 0]);
                            layer.position.setValue([-offsetW, -offsetH]);
                        }
                        else {
                            layer.scale.setValue([width / comp.width * 100.0, height / comp.height * 100.0]);
                        }
                        var videoFile = Settings.NewCacheAsset(Settings.NewCacheAssetName(".mov"));
                        RenderUtils.RenderComp(tempComp, RenderUtils.kNormalVideoRenderTemplate, videoFile, 0, true);
                        return ThumbnailTools.kMakeEditTemplateThumbnailWin.composeCmd(comp.id, tempComp.id, videoFile);
                    }
                    else {
                        alert("invalid");
                    }
                }
                else {
                    return "";
                }
            }
            return "";
        };
        ThumbnailTools.CreateEditTemplateThumbnail2 = function (cmd) {
            if (cmd.length > 0) {
                var cmdObj = JSON.parse(cmd);
                if (cmdObj.file) {
                    var file = new File(cmdObj.file);
                    if (file.exists) {
                        file.remove();
                    }
                }
                if (cmdObj.comp) {
                    var type = cmdObj.type;
                    var comp = DomUtils.GetItemById(cmdObj.comp);
                    var struct = new EditTemplateStructure(comp);
                    struct.removePlaceholders(type);
                }
                if (cmdObj.tempcomp) {
                    var tempcomp = DomUtils.GetItemById(cmdObj.tempcomp);
                }
                alert(VECleaner.kTranslator.mData.HOST_AssetTools_GIF2Video_Success);
            }
            else {
                alert(VECleaner.kTranslator.mData.HOST_AssetTools_GIF2Video_Fail);
            }
        };
        ThumbnailTools.CreateVideoTransitionThumbnail = function () {
            return ThumbnailTools.CreateEditTemplateThumbnail(EditTemplateType.kVideoTransition);
        };
        ThumbnailTools.CreateVideoEffectThumbnail = function () {
            return ThumbnailTools.CreateEditTemplateThumbnail(EditTemplateType.kVideoEffect);
        };
        ThumbnailTools.kMakeGIFThumbnailWin = null;
        ThumbnailTools.kMakePNGThumbnailWin = null;
        ThumbnailTools.kMakeEditTemplateThumbnailWin = null;
        return ThumbnailTools;
    }());
    var AllToolGroups = (function () {
        function AllToolGroups() {
            this.mActionGroups = [];
            var group1 = new ToolGroupInfo(VECleaner.kTranslator.mData.HOST_BasicTools_Name, VECleaner.kTranslator.mData.HOST_BasicTools_Description);
            group1.addTool(VECleaner.kTranslator.mData.HOST_BasicTools_BackupProject_Name, VECleaner.kTranslator.mData.HOST_BasicTools_BackupProject_Description, BasicTools.BackupProject, 1);
            group1.addTool(VECleaner.kTranslator.mData.HOST_BasicTools_Set8BitColorProject_Name, VECleaner.kTranslator.mData.HOST_BasicTools_Set8BitColorProject_Description, BasicTools.Set8BitColorProject, 2);
            group1.addTool(VECleaner.kTranslator.mData.HOST_BasicTools_RemoveExpressionsDeep_Name, VECleaner.kTranslator.mData.HOST_BasicTools_RemoveExpressionsDeep_Description, BasicTools.RemoveExpressionsDeep, 3);
            group1.addTool(VECleaner.kTranslator.mData.HOST_BasicTools_RemoveUnsedLayers_Name, VECleaner.kTranslator.mData.HOST_BasicTools_RemoveUnsedLayers_Description, BasicTools.RemoveUnsedLayers, 4);
            group1.addTool(VECleaner.kTranslator.mData.HOST_BasicTools_AddDefaultCamera_Name, VECleaner.kTranslator.mData.HOST_BasicTools_AddDefaultCamera_Description, BasicTools.AddDefaultCamera, 5);
            this.mActionGroups.push(group1);
            var group2 = new ToolGroupInfo(VECleaner.kTranslator.mData.HOST_MarkerTools_Name, VECleaner.kTranslator.mData.HOST_MarkerTools_Description);
            group2.addTool(VECleaner.kTranslator.mData.HOST_MarkerTools_AddEditImageMarker_Name, VECleaner.kTranslator.mData.HOST_MarkerTools_AddEditImageMarker_Description, MarkerTools.AddEditImageMarker, 6);
            group2.addTool(VECleaner.kTranslator.mData.HOST_MarkerTools_AddEditTextMarker_Name, VECleaner.kTranslator.mData.HOST_MarkerTools_AddEditTextMarker_Description, MarkerTools.AddEditTextMarker, 7);
            group2.addTool(VECleaner.kTranslator.mData.HOST_MarkerTools_ClearLayerMarkers_Name, VECleaner.kTranslator.mData.HOST_MarkerTools_ClearLayerMarkers_Description, MarkerTools.ClearLayerMarkers, 8);
            group2.addTool(VECleaner.kTranslator.mData.HOST_MarkerTools_ShowAllEditableLayers_Name, VECleaner.kTranslator.mData.HOST_MarkerTools_ShowAllEditableLayers_Description, MarkerTools.ShowAllEditableLayers, 9);
            this.mActionGroups.push(group2);
            var group7 = new ToolGroupInfo(VECleaner.kTranslator.mData.HOST_CropTools_Name, VECleaner.kTranslator.mData.HOST_CropTools_Description);
            group7.addTool(VECleaner.kTranslator.mData.HOST_CropTools_Crop2FitMasks_Name, VECleaner.kTranslator.mData.HOST_CropTools_Crop2FitMasks_Description, CropTools.CropLayer2FitMasks, 10);
            group7.addTool(VECleaner.kTranslator.mData.HOST_CropTools_SplitLayerMasks_Name, VECleaner.kTranslator.mData.HOST_CropTools_SplitLayerMasks_Description, CropTools.SplitLayerMasksKeepMask, 11);
            group7.addTool(VECleaner.kTranslator.mData.HOST_CropTools_SplitLayerMasksAndClear_Name, VECleaner.kTranslator.mData.HOST_CropTools_SplitLayerMasksAndClear_Description, CropTools.SplitLayerMasksWithoutMask, 12);
            this.mActionGroups.push(group7);
            var group3 = new ToolGroupInfo(VECleaner.kTranslator.mData.HOST_PreRenderTools_Name, VECleaner.kTranslator.mData.HOST_PreRenderTools_Description);
            group3.addTool(VECleaner.kTranslator.mData.HOST_PreRenderTools_PrecompLayers_Name, VECleaner.kTranslator.mData.HOST_PreRenderTools_PrecompLayers_Description, PreRenderTools.PrecompLayers, 13);
            group3.addTool(VECleaner.kTranslator.mData.HOST_PreRenderTools_RenderPreComp_Name, VECleaner.kTranslator.mData.HOST_PreRenderTools_RenderPreComp_Description, PreRenderTools.RenderPreComp, 14);
            group3.addTool(VECleaner.kTranslator.mData.HOST_PreRenderTools_RenderCompLayerEffects_Name, VECleaner.kTranslator.mData.HOST_PreRenderTools_RenderCompLayerEffects_Description, PreRenderTools.RenderCompLayerEffects, 15);
            group3.addTool(VECleaner.kTranslator.mData.HOST_PreRenderTools_Render3DLayers_Name, VECleaner.kTranslator.mData.HOST_PreRenderTools_Render3DLayers_Description, PreRenderTools.Render3DLayers, 16);
            group3.addTool(VECleaner.kTranslator.mData.HOST_PreRenderTools_RenderLayersInPlace_Name, VECleaner.kTranslator.mData.HOST_PreRenderTools_RenderLayersInPlace_Description, PreRenderTools.RenderLayersInPlace, 17);
            group3.addTool(VECleaner.kTranslator.mData.HOST_PreRenderTools_RenderAsImage_Name, VECleaner.kTranslator.mData.HOST_PreRenderTools_RenderAsImage_Description, PreRenderTools.RenderAsImage, 18);
            group3.addTool(VECleaner.kTranslator.mData.HOST_PreRenderTools_RenderAsAudio_Name, VECleaner.kTranslator.mData.HOST_PreRenderTools_RenderAsAudio_Description, PreRenderTools.CombineCompAudio, 19);
            group3.addTool(VECleaner.kTranslator.mData.HOST_PreRenderTools_ProcessColorGradeEffects_Name, VECleaner.kTranslator.mData.HOST_PreRenderTools_ProcessColorGradeEffects_Description, PreRenderTools.ProcessColorGradeEffects, 20);
            group3.addTool(VECleaner.kTranslator.mData.HOST_PreRenderTools_ProcessLayerMasks_Name, VECleaner.kTranslator.mData.HOST_PreRenderTools_ProcessLayerMasks_Description, PreRenderTools.ProcessSelectedLayerMasks, 21);
            group3.addTool(VECleaner.kTranslator.mData.HOST_PreRenderTools_ProcessCompMasks_Name, VECleaner.kTranslator.mData.HOST_PreRenderTools_ProcessCompMasks_Description, PreRenderTools.ProcessCompMasks, 22);
            group3.addTool(VECleaner.kTranslator.mData.HOST_PreRenderTools_CombineAndRenderCompLayers_Name, VECleaner.kTranslator.mData.HOST_PreRenderTools_CombineAndRenderCompLayers_Description, PreRenderTools.CombineAndRenderCompLayers, 23);
            this.mActionGroups.push(group3);
            var group4 = new ToolGroupInfo(VECleaner.kTranslator.mData.HOST_AssetTools_Name, VECleaner.kTranslator.mData.HOST_AssetTools_Description);
            group4.addTool(VECleaner.kTranslator.mData.HOST_AssetTools_HandlePremultipliedAlphaVideo_Name, VECleaner.kTranslator.mData.HOST_AssetTools_HandlePremultipliedAlphaVideo_Description, AssetTools.HandlePremultipliedAlphaVideo, 24);
            group4.addTool(VECleaner.kTranslator.mData.HOST_AssetTools_HandleNonSquarePixelItems_Name, VECleaner.kTranslator.mData.HOST_AssetTools_HandleNonSquarePixelItems_Description, AssetTools.HandleNonSquarePixelItems, 25);
            group4.addTwoStepTool(VECleaner.kTranslator.mData.HOST_AssetTools_CompressVideoSourceWithAlpha_Name, VECleaner.kTranslator.mData.HOST_AssetTools_CompressVideoSourceWithAlpha_Description, AssetTools.CompressVideoSourceWithAlphaStepOne, AssetTools.CompressVideoSourceWithAlphaStepTwo, 26);
            group4.addTwoStepTool(VECleaner.kTranslator.mData.HOST_AssetTools_CompressVideoSourceWithoutAlpha_Name, VECleaner.kTranslator.mData.HOST_AssetTools_CompressVideoSourceWithoutAlpha_Description, AssetTools.CompressVideoSourceWithoutAlphaStepOne, AssetTools.CompressVideoSourceWithoutAlphaStepTwo, 27);
            group4.addTwoStepTool(VECleaner.kTranslator.mData.HOST_AssetTools_CompressVideoSourceAdvance_Name, VECleaner.kTranslator.mData.HOST_AssetTools_CompressVideoSourceAdvance_Description, AssetTools.CompressVideoSourceAdvance, AssetTools.CompressVideoSourceAdvanceStepTwo, 28);
            group4.addTwoStepTool(VECleaner.kTranslator.mData.HOST_AssetTools_GIF2Video_Name, VECleaner.kTranslator.mData.HOST_AssetTools_GIF2Video_Description, AssetTools.CreateGifFromVideo, AssetTools.CreateGifFromVideo2, 29);
            group4.addTwoStepTool(VECleaner.kTranslator.mData.HOST_AssetTools_Layer2PNGs_Name, VECleaner.kTranslator.mData.HOST_AssetTools_Layer2PNGs_Description, AssetTools.CreatePNGSequenceFromLayer, AssetTools.CreatePNGSequenceFromVideo2, 30);
            group4.addTwoStepTool(VECleaner.kTranslator.mData.HOST_AssetTools_Video2PNGs_Name, VECleaner.kTranslator.mData.HOST_AssetTools_Video2PNGs_Description, AssetTools.CreatePNGSequenceFromVideoFile, AssetTools.CreatePNGSequenceFromVideo2, 31);
            group4.addTool(VECleaner.kTranslator.mData.HOST_AssetTools_RemoveUnusedVideoFiles_Name, VECleaner.kTranslator.mData.HOST_AssetTools_RemoveUnusedVideoFiles_Description, AssetTools.RemoveUnusedVideoFiles, 32);
            this.mActionGroups.push(group4);
            var thumbnailGroup = new ToolGroupInfo(VECleaner.kTranslator.mData.HOST_ThumbnailTools_Name, VECleaner.kTranslator.mData.HOST_ThumbnailTools_Description);
            thumbnailGroup.addTwoStepTool(VECleaner.kTranslator.mData.HOST_ThumbnailTools_GIF_Name, VECleaner.kTranslator.mData.HOST_ThumbnailTools_GIF_Description, ThumbnailTools.CreateGIFThumbnail, ThumbnailTools.CreateGIFThumbnail2, 33);
            thumbnailGroup.addTool(VECleaner.kTranslator.mData.HOST_ThumbnailTools_PNG_Name, VECleaner.kTranslator.mData.HOST_ThumbnailTools_PNG_Description, ThumbnailTools.CreatePNGThumbnail, 34);
            thumbnailGroup.addTwoStepTool(VECleaner.kTranslator.mData.HOST_ThumbnailTools_VT_Name, VECleaner.kTranslator.mData.HOST_ThumbnailTools_VT_Description, ThumbnailTools.CreateVideoTransitionThumbnail, ThumbnailTools.CreateEditTemplateThumbnail2, 35);
            thumbnailGroup.addTwoStepTool(VECleaner.kTranslator.mData.HOST_ThumbnailTools_VE_Name, VECleaner.kTranslator.mData.HOST_ThumbnailTools_VE_Description, ThumbnailTools.CreateVideoEffectThumbnail, ThumbnailTools.CreateEditTemplateThumbnail2, 36);
            this.mActionGroups.push(thumbnailGroup);
            var group5 = new ToolGroupInfo(VECleaner.kTranslator.mData.HOST_SearchTools_Name, VECleaner.kTranslator.mData.HOST_SearchTools_Description);
            group5.addTool(VECleaner.kTranslator.mData.HOST_SearchTools_FindBigVideoFiles_Name, VECleaner.kTranslator.mData.HOST_SearchTools_FindBigVideoFiles_Description, SearchTools.FindBigVideoFiles, 37);
            group5.addTool(VECleaner.kTranslator.mData.HOST_SearchTools_Find3DLayers_Name, VECleaner.kTranslator.mData.HOST_SearchTools_Find3DLayers_Description, SearchTools.Find3DLayers, 38);
            group5.addTool(VECleaner.kTranslator.mData.HOST_SearchTools_FindUnsupportedBlendMode_Name, VECleaner.kTranslator.mData.HOST_SearchTools_FindUnsupportedBlendMode_Description, SearchTools.FindUnsupportedBlendMode, 39);
            this.mActionGroups.push(group5);
            var group6 = new ToolGroupInfo(VECleaner.kTranslator.mData.HOST_TemplateConvertionTools_Name, VECleaner.kTranslator.mData.HOST_TemplateConvertionTools_Description);
            group6.addTool(VECleaner.kTranslator.mData.HOST_TemplateConvertionTools_ConvertVer1TemplateToVer2Template_Name, VECleaner.kTranslator.mData.HOST_TemplateConvertionTools_ConvertVer1TemplateToVer2Template_Description, TemplateConvertionTools.ConvertVer1TemplateToVer2Template, 40, false);
            group6.addTool(VECleaner.kTranslator.mData.HOST_TemplateConvertionTools_LUT2Filter_Name, VECleaner.kTranslator.mData.HOST_TemplateConvertionTools_LUT2Filter_Description, TemplateConvertionTools.ConvertLUTImage2EditFilter, 41, false);
            group6.addTool(VECleaner.kTranslator.mData.HOST_TemplateConvertionTools_ReorderGroupByInpoint_Name, VECleaner.kTranslator.mData.HOST_TemplateConvertionTools_ReorderGroupByInpoint_Description, TemplateUIDataUtils.ReorderTemplateGroupByInpoint, 42, false);
            group6.addTool(VECleaner.kTranslator.mData.HOST_TemplateConvertionTools_FixTempl2_Name, VECleaner.kTranslator.mData.HOST_TemplateConvertionTools_FixTempl2_Description, TemplateUIDataUtils.FixNormalTemplate2InfoLost, 43, false);
            this.mActionGroups.push(group6);
        }
        AllToolGroups.prototype.getJsonString = function () {
            var json = new JsonWriter();
            json.startArray();
            for (var i = 0; i < this.mActionGroups.length; i++) {
                var group = this.mActionGroups[i];
                json.startObject();
                json.putKey("name");
                json.putString(group.mName);
                json.putKey("description");
                json.putString(group.mDescription);
                json.putKey("actions");
                json.startArray();
                for (var a = 0; a < group.mTools.length; a++) {
                    var action = group.mTools[a];
                    json.startObject();
                    json.putKey("g");
                    json.putNumber(i);
                    json.putKey("a");
                    json.putNumber(a);
                    json.putKey("name");
                    json.putString(action.mName);
                    json.putKey("diskID");
                    json.putNumber(action.mDiskID);
                    json.putKey("description");
                    json.putString(action.mDescription);
                    json.putKey("twoStep");
                    json.putBoolean(action.isTwoStep());
                    json.endObject();
                }
                json.endArray();
                json.endObject();
            }
            json.endArray();
            return json.getContent();
        };
        return AllToolGroups;
    }());
    VECleaner.AllToolGroups = AllToolGroups;
    VECleaner.kAllToolGroups = null;
    function GetAllActionGroupsContent() {
        if (VECleaner.kAllToolGroups == null) {
            VECleaner.kAllToolGroups = new AllToolGroups();
        }
        return VECleaner.kAllToolGroups.getJsonString();
    }
    VECleaner.GetAllActionGroupsContent = GetAllActionGroupsContent;
    function ActionSafetyCheck(g, a) {
        if (g >= 0 && g < VECleaner.kAllToolGroups.mActionGroups.length) {
            var group = VECleaner.kAllToolGroups.mActionGroups[g];
            if (a >= 0 && a < group.mTools.length) {
                if (group.mTools[a].mNeedSaveProject) {
                    var dir = Settings.GetProjectFolder();
                    if (dir == null) {
                        alert(VECleaner.kTranslator.mData.HOST_ActionSafetyCheck_msg1);
                    }
                    return dir != null;
                }
                else {
                    return true;
                }
            }
        }
        return false;
    }
    VECleaner.ActionSafetyCheck = ActionSafetyCheck;
    function RunAction(g, a) {
        if (VECleaner.kAllToolGroups == null) {
            VECleaner.kAllToolGroups = new AllToolGroups();
        }
        if (g >= 0 && g < VECleaner.kAllToolGroups.mActionGroups.length) {
            var group = VECleaner.kAllToolGroups.mActionGroups[g];
            if (a >= 0 && a < group.mTools.length) {
                app.beginSuppressDialogs();
                group.mTools[a].trigger();
                app.endSuppressDialogs(false);
            }
        }
    }
    VECleaner.RunAction = RunAction;
    function RunActionStepOne(g, a) {
        if (VECleaner.kAllToolGroups == null) {
            VECleaner.kAllToolGroups = new AllToolGroups();
        }
        if (g >= 0 && g < VECleaner.kAllToolGroups.mActionGroups.length) {
            var group = VECleaner.kAllToolGroups.mActionGroups[g];
            if (a >= 0 && a < group.mTools.length) {
                var action = group.mTools[a];
                if (action.isTwoStep()) {
                    app.beginSuppressDialogs();
                    var ret = action.stepOne();
                    app.endSuppressDialogs(false);
                    return ret;
                }
            }
        }
        return "";
    }
    VECleaner.RunActionStepOne = RunActionStepOne;
    function RunActionStepTwo(g, a, cmd) {
        if (cmd.length > 0) {
            if (VECleaner.kAllToolGroups == null) {
                VECleaner.kAllToolGroups = new AllToolGroups();
            }
            if (g >= 0 && g < VECleaner.kAllToolGroups.mActionGroups.length) {
                var group = VECleaner.kAllToolGroups.mActionGroups[g];
                if (a >= 0 && a < group.mTools.length) {
                    var action = group.mTools[a];
                    if (action.isTwoStep()) {
                        action.stepTwo(cmd);
                    }
                }
            }
        }
    }
    VECleaner.RunActionStepTwo = RunActionStepTwo;
    function isSecurityPrefSet() {
        var securitySetting = app.preferences.getPrefAsLong("Main Pref Section", "Pref_SCRIPTING_FILE_NETWORK_SECURITY");
        return (securitySetting == 1);
    }
    VECleaner.isSecurityPrefSet = isSecurityPrefSet;
})(VECleaner || (VECleaner = {}));
